@clairejs/server 3.15.1 → 3.15.2
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 +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
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 i=t();for(var o in i)("object"==typeof exports?exports:e)[o]=i[o]}}(global,(()=>(()=>{"use strict";var e={8985:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractController=void 0;const o=i(5007);class AbstractController extends o.Transactionable{}t.AbstractController=AbstractController},2872:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},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={}))},5007:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Transactionable=void 0;const n=i(2318),r=i(7756);t.Transactionable=class Transactionable{constructor(e){this.transactionFactory=e}createTransaction(){return o(this,void 0,void 0,(function*(){if(!this.transactionFactory)throw n.Errors.SYSTEM_ERROR("Transaction factory not injected to this class");return this.transactionFactory.createTransaction()}))}getCurrentTransaction(){return o(this,void 0,void 0,(function*(){return(0,r.getTransactionFromContext)(this)}))}}},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=void 0,t.ExitCode={SIGTERM_INTERUPTION:-1,SIGINT_INTERUPTION:-2,UNCAUGHT_EXCEPTION:-3,UNHANDLED_REJECTION:-4}},7678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Controller=void 0;const o=i(2318);t.Controller=e=>t=>{(0,o.getServiceProvider)().register(t,"singleton");(0,o.initObjectMetadata)(t.prototype).permissionGroup=null==e?void 0:e.permissionGroup}},4435:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},4972:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},1870:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},7540:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},7380:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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(i,o){t(i,o,e)}},s=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FileManageController=void 0;const a=i(2318),d=i(8903),l=i(6004),c=i(2417),u=i(7179),p=i(7724);let h=class FileManageController extends l.AbstractHttpController{constructor(e){super(null),this.fileService=e}moveFile(e){return s(this,void 0,void 0,(function*(){return yield this.fileService.moveObject(e.operations),d.ResponseBuilder.success()}))}copyFile(e){return s(this,void 0,void 0,(function*(){return yield this.fileService.copyObject(e.operations),d.ResponseBuilder.success()}))}removeFile(e){return s(this,void 0,void 0,(function*(){return yield this.fileService.removeObject(e.uris),d.ResponseBuilder.success()}))}getFileAccessUrl(e){return s(this,void 0,void 0,(function*(){const t=yield this.fileService.getAccessUrls(e.uris,e.public);return d.ResponseBuilder.json({urls:t}).get()}))}getFileInfo(e){return s(this,void 0,void 0,(function*(){const t={fileInfos:(yield this.fileService.getFileSize(e.uris)).map((e=>({fileSizeBytes:e})))};return d.ResponseBuilder.json(t).get()}))}};o([(0,c.Post)("/file/move"),r(0,(0,c.Body)()),n("design:type",Function),n("design:paramtypes",[p.MoveFileRequest]),n("design:returntype",Promise)],h.prototype,"moveFile",null),o([(0,c.Post)("/file/copy"),r(0,(0,c.Body)()),n("design:type",Function),n("design:paramtypes",[p.MoveFileRequest]),n("design:returntype",Promise)],h.prototype,"copyFile",null),o([(0,c.Post)("/file/remove"),r(0,(0,c.Body)()),n("design:type",Function),n("design:paramtypes",[p.RemoveFileRequest]),n("design:returntype",Promise)],h.prototype,"removeFile",null),o([(0,c.Get)("/file"),(0,c.ApiResponse)(p.GetFileAccessUrlResponse),r(0,(0,c.Queries)()),n("design:type",Function),n("design:paramtypes",[p.GetFileAccessUrlRequest]),n("design:returntype",Promise)],h.prototype,"getFileAccessUrl",null),o([(0,c.Get)("/file/info"),(0,c.ApiResponse)(p.GetFileInfoResponse),r(0,(0,c.Queries)()),n("design:type",Function),n("design:paramtypes",[p.GetFileInfoRequest]),n("design:returntype",Promise)],h.prototype,"getFileInfo",null),h=o([(0,a.Injectable)(),n("design:paramtypes",[u.AbstractFileService])],h),t.FileManageController=h},8037:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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(i,o){t(i,o,e)}},s=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FileUploadController=void 0;const d=i(2318),l=a(i(7325)),c=i(8903),u=i(6004),p=i(2417),h=i(7179),f=i(7724);let v=class FileUploadController extends u.AbstractHttpController{constructor(e,t){super(null),this.fileService=e,this.allowedUploadExtensions=t}getUploadUrl(e){var t;return s(this,void 0,void 0,(function*(){const i=null===(t=e.extension)||void 0===t?void 0:t.toLowerCase();if(i&&!this.allowedUploadExtensions.includes(i))throw d.Errors.VALIDATION_ERROR("Not allowed file extension");const o=yield this.fileService.getUploadUrlForTempUri(`tmp/${l.default.generate({length:64})}${i?`.${i}`:""}`);return c.ResponseBuilder.json(o).get()}))}getMultipleUploadUrls(e){return s(this,void 0,void 0,(function*(){if(e.extensions.some((e=>!this.allowedUploadExtensions.includes(e))))throw d.Errors.VALIDATION_ERROR("Not allowed file extension");const t=yield Promise.all(e.extensions.map((e=>this.fileService.getUploadUrlForTempUri(`tmp/${l.default.generate({length:64})}${e?`.${e}`:""}`))));return c.ResponseBuilder.json({files:t}).get()}))}};o([(0,p.Get)("/upload-url"),(0,p.ApiResponse)(f.GetUploadUrlResponseBody),r(0,(0,p.Queries)()),n("design:type",Function),n("design:paramtypes",[f.GetUploadUrlQueries]),n("design:returntype",Promise)],v.prototype,"getUploadUrl",null),o([(0,p.Get)("/upload-urls"),(0,p.ApiResponse)(f.GetMultipleUploadResponseBody),r(0,(0,p.Queries)()),n("design:type",Function),n("design:paramtypes",[f.GetMultipleUploadUrlsQueries]),n("design:returntype",Promise)],v.prototype,"getMultipleUploadUrls",null),v=o([(0,d.Injectable)(),n("design:paramtypes",[h.AbstractFileService,Array])],v),t.FileUploadController=v},2345:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UserVerificationMethod=t.CacheOperation=void 0,function(e){e.GET="get",e.KEYS="keys",e.HGET="hget",e.HKEYS="hkeys",e.FLUSH="flush"}(t.CacheOperation||(t.CacheOperation={})),function(e){e.SMS_OTP="SMS",e.VOICE_OTP="VOICE",e.MANUAL_OTP="MANUAL"}(t.UserVerificationMethod||(t.UserVerificationMethod={}))},7724:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};Object.defineProperty(t,"__esModule",{value:!0}),t.GetFileInfoResponse=t.FileInfo=t.GetFileInfoRequest=t.GetFileAccessUrlResponse=t.GetFileAccessUrlRequest=t.RemoveFileRequest=t.MoveFileRequest=t.MoveOperation=t.GetMultipleUploadResponseBody=t.GetMultipleUploadUrlsQueries=t.GetUploadUrlResponseBody=t.GetUploadUrlQueries=void 0;const r=i(2318);let s=class GetUploadUrlQueries{};o([(0,r.Field)({description:"Extension of the file to be uploaded (without dot)"}),n("design:type",String)],s.prototype,"extension",void 0),s=o([(0,r.Data)()],s),t.GetUploadUrlQueries=s;let a=class GetUploadUrlResponseBody{};o([(0,r.Field)({description:"Object key of file that store in the server",isRequired:!0}),n("design:type",String)],a.prototype,"objectKey",void 0),o([(0,r.Field)({description:"Presigned URl to put the file to server"}),n("design:type",String)],a.prototype,"putPresignedUrl",void 0),o([(0,r.Field)({description:"Presigned URL to remove the temporary file from server",isRequired:!0}),n("design:type",String)],a.prototype,"deletePresignedUrl",void 0),a=o([(0,r.Data)()],a),t.GetUploadUrlResponseBody=a;let d=class GetMultipleUploadUrlsQueries{};o([(0,r.Field)({description:"Extensions of those files",isRequired:!0,vectorProps:{allowDuplicated:!0}}),n("design:type",Array)],d.prototype,"extensions",void 0),d=o([(0,r.Data)({relaxed:!0})],d),t.GetMultipleUploadUrlsQueries=d;class GetMultipleUploadResponseBody{}o([(0,r.Field)(Object.assign({description:"Upload urls for files",vectorProps:{elementDataType:r.DataType.OBJECT}},(0,r.ElementDto)(a))),n("design:type",Array)],GetMultipleUploadResponseBody.prototype,"files",void 0),t.GetMultipleUploadResponseBody=GetMultipleUploadResponseBody;let l=class MoveOperation{};o([(0,r.Field)({description:"Source of move operation",isRequired:!0}),n("design:type",String)],l.prototype,"fromURI",void 0),o([(0,r.Field)({description:"Destination of move operation",isRequired:!0}),n("design:type",String)],l.prototype,"toURI",void 0),l=o([(0,r.Data)()],l),t.MoveOperation=l;let c=class MoveFileRequest{};o([(0,r.Field)(Object.assign({description:"All move operations",isRequired:!0,vectorProps:{elementDataType:r.DataType.OBJECT}},(0,r.ElementDto)(l))),n("design:type",Array)],c.prototype,"operations",void 0),c=o([(0,r.Data)()],c),t.MoveFileRequest=c;let u=class RemoveFileRequest{};o([(0,r.Field)({description:"File URIs to remove",isRequired:!0,vectorProps:{elementDataType:r.DataType.STRING}}),n("design:type",Array)],u.prototype,"uris",void 0),u=o([(0,r.Data)()],u),t.RemoveFileRequest=u;let p=class GetFileAccessUrlRequest{};o([(0,r.Field)({description:"All URIs to get access link",isRequired:!0,vectorProps:{elementDataType:r.DataType.STRING}}),n("design:type",Array)],p.prototype,"uris",void 0),o([(0,r.Field)({description:"Whether to get public or private link",isRequired:!0}),n("design:type",Boolean)],p.prototype,"public",void 0),p=o([(0,r.Data)({relaxed:!0})],p),t.GetFileAccessUrlRequest=p;let h=class GetFileAccessUrlResponse{};o([(0,r.Field)({description:"File access URLs",isRequired:!0,vectorProps:{elementDataType:r.DataType.STRING}}),n("design:type",Array)],h.prototype,"urls",void 0),h=o([(0,r.Data)()],h),t.GetFileAccessUrlResponse=h;let f=class GetFileInfoRequest{};o([(0,r.Field)({description:"File URIs to get info",isRequired:!0,vectorProps:{elementDataType:r.DataType.STRING}}),n("design:type",Array)],f.prototype,"uris",void 0),f=o([(0,r.Data)({relaxed:!0})],f),t.GetFileInfoRequest=f;let v=class FileInfo{};o([(0,r.Field)({description:"Size of file in bytes",isRequired:!0}),n("design:type",Number)],v.prototype,"fileSizeBytes",void 0),v=o([(0,r.Data)()],v),t.FileInfo=v;let y=class GetFileInfoResponse{};o([(0,r.Field)(Object.assign({description:"File infos",isRequired:!0,vectorProps:{elementDataType:r.DataType.OBJECT}},(0,r.ElementDto)(v))),n("design:type",Array)],y.prototype,"fileInfos",void 0),y=o([(0,r.Data)()],y),t.GetFileInfoResponse=y},5709:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRequestAuthorizer=void 0;t.AbstractRequestAuthorizer=class AbstractRequestAuthorizer{}},1532:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HttpRequest=void 0;const o=i(2318);t.HttpRequest=class HttpRequest{constructor(e,t){this.endpointMetadata=t,this.valueHolder={},this.params={},this.query={},this.body={},this.clientIP=e.clientIP,this.method=e.method,this.pathName=e.pathName,this.headers=e.headers||{},this.cookies=e.cookies||{},this.hash=e.hash||"",this.params.data=e.params||{},this.query.data=e.query||{},this.body.data=e.body||{}}jsonParsing(e,t){const i=Object.assign({},e);for(const n of t.fields)try{(void 0!==e[n.name]||n.isRequired)&&(i[n.name]=JSON.parse(e[n.name]))}catch(e){throw o.Errors.VALIDATION_ERROR(`JSON parsing failed for field ${n.name}`)}return i}getAuthInfo(){return this.authInfo}setAuthInfo(e){this.authInfo=e}getParams(){var e;return(null===(e=this.endpointMetadata)||void 0===e?void 0:e.paramsValidationDto)&&!this.params.validated&&(this.params.data=(0,o.validateData)(this.params.data,this.endpointMetadata.paramsValidationDto),this.params.validated=!0),this.params.data}getQuery(){var e;return(null===(e=this.endpointMetadata)||void 0===e?void 0:e.queriesValidationDto)&&!this.query.validated&&(this.query.data=(0,o.validateData)(this.jsonParsing(this.query.data,this.endpointMetadata.queriesValidationDto),this.endpointMetadata.queriesValidationDto),this.query.validated=!0),this.query.data}getBody(){var e;return this.endpointMetadata&&(this.endpointMetadata.httpMethod===o.HttpMethod.POST||this.endpointMetadata.httpMethod===o.HttpMethod.PUT)&&(null===(e=this.endpointMetadata)||void 0===e?void 0:e.bodyValidationDto)&&(this.body.data=(0,o.validateData)(this.body.data,this.endpointMetadata.bodyValidationDto,!1),this.body.validated=!0),this.body.data}}},8903:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ResponseBuilder=t.HttpResponse=void 0;class HttpResponse{constructor(){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,i){return this.response.cookies[e]={value:t,options:i},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=403,t.response.value=e,t.response}}t.ResponseBuilder=ResponseBuilder},6004:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpController=void 0;const o=i(2318),n=i(8985);class AbstractHttpController extends n.AbstractController{constructor(e){super(e),this.databaseAdapter=e}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}))):[]}}t.AbstractHttpController=AbstractHttpController},225:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpMiddleware=void 0;t.AbstractHttpMiddleware=class AbstractHttpMiddleware{}},767:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpRequestHandler=void 0;const n=i(2318),r=i(9202),s=i(6004);t.AbstractHttpRequestHandler=class AbstractHttpRequestHandler{constructor(e,t){this.mountPoint=e,this.logger=t}resolverMountPoint(e,t){if(!e)return"";const i=[];return i.push(...t),i.reduce(((e,t)=>`${e}/${t}`),"").replace(/(\/)\/+/g,"$1")}getMountedEndpointInfo(){var e,t,i;return o(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const o=[],a=(0,n.getServiceProvider)().getInjector(),d=a.resolveMultiple(s.AbstractHttpController);yield a.initInstances();for(const e of d){const t=(0,n.getObjectMetadata)(e.constructor),i=e.getEndpointMetadata();for(const r of i){const i={mount:r.httpMethod===n.SocketMethod.MESSAGE?r.url:this.resolverMountPoint(t,[this.mountPoint||"/",r.url]),httpMethod:r.httpMethod,controller:e,handlerFunctionName:r.name};o.push({endpointMetadata:r,endpoint:i})}}const l=[];for(const n of o){const o=l.find((e=>e.endpoint.mount===n.endpoint.mount&&e.endpoint.httpMethod===n.endpoint.httpMethod));o?null===(e=this.logger)||void 0===e||e.warn(`Implicit overriding endpoint: ${(0,r.getEndpointId)(o.endpoint)} of ${null===(t=o.endpoint.controller)||void 0===t?void 0:t.constructor.name}:${o.endpoint.handlerFunctionName}`,`Ignore ${(0,r.getEndpointId)(n.endpoint)} of ${null===(i=n.endpoint.controller)||void 0===i?void 0:i.constructor.name}:${n.endpoint.handlerFunctionName}`):l.push(n)}this.mountedEndpointInfo=l}return this.mountedEndpointInfo}))}}},7282:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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(i,o){t(i,o,e)}},s=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},a=this&&this.__rest||function(e,t){var i={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++)t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}return i};Object.defineProperty(t,"__esModule",{value:!0}),t.CrudHttpController=void 0;const d=i(2318),l=i(7756),c=i(1532),u=i(8903),p=i(4638),h=i(2417),f=i(6004),v=i(3198),y=i(1071);class CrudHttpController extends f.AbstractHttpController{constructor(e,t,i){super(i),this.model=e,this.crudRepository=t,this.databaseAdapter=i,this.modelMetadata=(0,d.getObjectMetadata)(e)}getMountedUrl(){return`/${this.model.name.toLowerCase()}`}getAuthProvider(){return s(this,void 0,void 0,(function*(){if(void 0===this.principalResolver){const e=(0,d.getServiceProvider)().getInjector();this.principalResolver=e.resolveOptional(p.AbstractPrincipalResolver)||null,yield e.initInstances()}return this.principalResolver}))}createManyEndpoinMetadata(){const e={};return e.httpMethod=d.HttpMethod.POST,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.createMany.name,e.displayName="createMany"+this.model.name,e.bodyValidationDto=(0,d.getCreateManyBodyValidator)(this.modelMetadata),e.responseValidationDto=(0,d.getCreateManyResponseValidator)(this.modelMetadata),e.accessConditions=[],e.params={0:{source:"raw"}},e}getManyEndpointMetadata(){const e={};return e.httpMethod=d.HttpMethod.GET,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.getMany.name,e.displayName="getAll"+this.model.name,e.queriesValidationDto=(0,d.getGetManyQueryValidator)(this.modelMetadata),e.responseValidationDto=(0,d.getGetManyResponseValidator)(this.modelMetadata),e.accessConditions=[(0,y.FilterModelFieldAccessCondition)(this.model,"model_projection",(e=>e.getQuery().projection)),v.MaximumQueryLimit],e.params={0:{source:"raw"}},e}updateManyEndpointMetadata(){const e={};return e.httpMethod=d.HttpMethod.PUT,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.updateMany.name,e.displayName="update"+this.model.name,e.queriesValidationDto=(0,d.getUpdateManyQueryValidator)(this.modelMetadata),e.bodyValidationDto=(0,d.getUpdateManyBodyValidator)(this.modelMetadata),e.responseValidationDto=(0,d.getUpdateManyResponseValidator)(this.modelMetadata),e.accessConditions=[(0,y.FilterModelFieldAccessCondition)(this.model,"restrict_update_fields",(e=>{const t=e.getBody().update;return t?Object.keys((0,d.leanData)(t)):[]}))],e.params={0:{source:"raw"}},e}updateRecordsEndpointMetadata(){const e={};return e.httpMethod=d.HttpMethod.PUT,e.url=`${this.getMountedUrl()}/records`,e.name=CrudHttpController.prototype.updateRecords.name,e.displayName="updateRecords"+this.model.name,e.queriesValidationDto=(0,d.getUpdateRecordsQueryValidator)(),e.bodyValidationDto=(0,d.getUpdateRecordsBodyValidator)(this.modelMetadata),e.responseValidationDto=(0,d.getUpdateManyResponseValidator)(this.modelMetadata),e.accessConditions=[(0,y.FilterModelFieldAccessCondition)(this.model,"restrict_update_fields",(e=>e.getBody().records.flatMap((e=>{var{id:t}=e,i=a(e,["id"]);return Object.keys(i)})).reduce(d.uniqueReducer,[])))],e}deleteManyEndpoinMetadata(){const e={};return e.httpMethod=d.HttpMethod.DEL,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.deleteMany.name,e.displayName="delete"+this.model.name,e.queriesValidationDto=(0,d.getUpdateManyQueryValidator)(this.modelMetadata),e.responseValidationDto=(0,d.getUpdateManyResponseValidator)(this.modelMetadata),e.params={0:{source:"raw"}},e.accessConditions=[],e}getEndpointMetadata(){var e,t,i,o;let n=super.getEndpointMetadata();const r=[];(null===(e=this.modelMetadata.ignoreCrud)||void 0===e?void 0:e.includes(d.HttpMethod.GET))?n=n.filter((e=>e.name!==CrudHttpController.prototype.getMany.name)):r.push(this.getManyEndpointMetadata()),(null===(t=this.modelMetadata.ignoreCrud)||void 0===t?void 0:t.includes(d.HttpMethod.POST))?n=n.filter((e=>e.name!==CrudHttpController.prototype.createMany.name)):r.push(this.createManyEndpoinMetadata()),(null===(i=this.modelMetadata.ignoreCrud)||void 0===i?void 0:i.includes(d.HttpMethod.PUT))?n=n.filter((e=>e.name!==CrudHttpController.prototype.updateMany.name)):(r.push(this.updateManyEndpointMetadata()),r.push(this.updateRecordsEndpointMetadata())),(null===(o=this.modelMetadata.ignoreCrud)||void 0===o?void 0:o.includes(d.HttpMethod.DEL))?n=n.filter((e=>e.name!==CrudHttpController.prototype.deleteMany.name)):r.push(this.deleteManyEndpoinMetadata());for(const e of r){const t=n.findIndex((t=>t.httpMethod===e.httpMethod&&t.url===e.url||t.name===e.name&&(!t.httpMethod||!t.url)));t>=0?n[t]=Object.assign(Object.assign(Object.assign({},e),n[t]),{accessConditions:[...e.accessConditions||[],...n[t].accessConditions||[]]}):n.push(e)}return n}updateRecords(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),i=yield this.getAuthProvider(),o=i&&(yield i.resolvePrincipal(e)),n=e.getBody(),r=e.getQuery(),s={modified:(yield Promise.all(n.records.map((e=>this.crudRepository.updateMany({principal:o,queries:Object.assign(Object.assign({},r),{fields:{id:[e.id]}}),body:{update:(0,d.omitData)(e,["id"])},tx:t}))))).map((e=>e.modified[0]))};return u.ResponseBuilder.json(s).get()}))}createMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),i=yield this.getAuthProvider(),o=i&&(yield i.resolvePrincipal(e)),n=yield this.crudRepository.createMany({principal:o,body:e.getBody(),tx:t});return u.ResponseBuilder.json(n).get()}))}getMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.crudRepository.getMany({queries:e.getQuery(),queryProvider:this.databaseAdapter});return u.ResponseBuilder.json(t).get()}))}updateMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),i=yield this.getAuthProvider(),o=i&&(yield i.resolvePrincipal(e)),n=yield this.crudRepository.updateMany({principal:o,queries:e.getQuery(),body:e.getBody(),tx:t});return u.ResponseBuilder.json(n).get()}))}deleteMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),i=yield this.crudRepository.deleteMany({queries:e.getQuery(),tx:t});return u.ResponseBuilder.json({modified:i.modified.map((e=>e.id)).map((e=>({id:e})))}).get()}))}}o([(0,l.Transactional)(l.PropagationMode.INHERIT_OR_CREATE),(0,h.ApiDescription)("Update records of this table."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),n("design:type",Function),n("design:paramtypes",[c.HttpRequest]),n("design:returntype",Promise)],CrudHttpController.prototype,"updateRecords",null),o([(0,l.Transactional)(l.PropagationMode.INHERIT_OR_CREATE),(0,h.ApiDescription)("Create records of this table."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),n("design:type",Function),n("design:paramtypes",[c.HttpRequest]),n("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),o([(0,h.AccessCondition)([]),(0,h.ApiDescription)("Get records of this table."),r(0,(0,h.Raw)()),n("design:type",Function),n("design:paramtypes",[c.HttpRequest]),n("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),o([(0,l.Transactional)(l.PropagationMode.INHERIT_OR_CREATE),(0,h.ApiDescription)("Find and update records which match search condition."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),n("design:type",Function),n("design:paramtypes",[c.HttpRequest]),n("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),o([(0,l.Transactional)(l.PropagationMode.INHERIT_OR_CREATE),(0,h.ApiDescription)("Find and remove records which match search condition."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),n("design:type",Function),n("design:paramtypes",[c.HttpRequest]),n("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},5879:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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=i(2318),d=s(i(7325)),l=s(i(9215)),c=i(99),u=s(i(9103)),p=i(8903),h=i(4638),f=i(1532),v=i(5709),y=i(225),g=i(767);let m=class DefaultHttpRequestHandler extends g.AbstractHttpRequestHandler{constructor(e,t,i){super("",e),this.logger=e,this.authorizationProvider=t,this.principalResolver=i,this._middleware=null}handleRequest(e,t){return r(this,void 0,void 0,(function*(){const i=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.headers;case"raw":return t}})),o=yield e.endpoint.controller[e.endpointMetadata.name](...i);return e.endpointMetadata.responseValidationDto&&(o.value=(0,a.stripData)(o.value,e.endpointMetadata.responseValidationDto)),o}))}exit(){}getResponse(e){return r(this,void 0,void 0,(function*(){let t=new p.HttpResponse;const i=e.method,o=(0,l.default)({url:e.fullPath});let n={};const r=(yield this.getMountedEndpointInfo()).find((e=>{const t=e.endpointMetadata.httpMethod===i&&(0,c.match)(e.endpointMetadata.url,{decode:decodeURIComponent})(o.pathname||"/");return!!t&&(n=t,!0)}));if(!r)throw this.logger.debug(e),a.Errors.NOT_FOUND("Handler not found");const s=new f.HttpRequest({clientIP:e.clientIP,method:i,headers:e.headers,pathName:o.pathname||"",hash:o.hash||"",query:u.default.parse(decodeURIComponent(o.search||"")),params:n.params,body:e.body,cookies:e.cookies},r.endpointMetadata),d=yield this.principalResolver.resolvePrincipal(s);s.setAuthInfo(d),r.endpointMetadata.openAccess||(yield this.authorizationProvider.authorize(s,r));const h=yield this.getMiddleware();for(const e of h){if(!(yield e.intercept(s,t,r.endpointMetadata)))return t}const v=yield this.handleRequest(r,s);return v.code=v.code||t.code||200,v.value=v.value||t.value,v.headers=Object.assign(Object.assign({},t.headers),v.headers),v.cookies=Object.assign(Object.assign({},t.cookies),v.cookies),v}))}handle(e){return r(this,void 0,void 0,(function*(){const t=d.default.generate();this.logger.info(`===== HANDLING REQUEST: ${t} - ${e.method}:${e.fullPath}`);try{const i=yield this.getResponse(e);if(!(i&&i instanceof p.HttpResponse))throw a.Errors.SYSTEM_ERROR(`Invalid response value returned, required instance of ${p.HttpResponse.name}, found ${i?null==i?void 0:i.constructor.name:i}`);return this.logger.info(`===== REQUEST SUCCESS: ${t} - ${e.method}:${e.fullPath}`),i}catch(i){this.logger.error(i);const o=p.ResponseBuilder.json({name:i.name,message:i.message}).status(i.code||500).get();return this.logger.info(`===== REQUEST FAILED: ${t} - ${e.method}:${e.fullPath}, code: ${o.code}`,o.value),o}}))}getMiddleware(){return r(this,void 0,void 0,(function*(){if(null===this._middleware){const e=(0,a.getServiceProvider)().getInjector();this._middleware=e.resolveMultiple(y.AbstractHttpMiddleware),yield e.initInstances()}return this._middleware}))}};m=o([(0,a.Injectable)(),(0,a.LogContext)(),n("design:paramtypes",[a.AbstractLogger,v.AbstractRequestAuthorizer,h.AbstractPrincipalResolver])],m),t.DefaultHttpRequestHandler=m},2417:(e,t,i)=>{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.Head=t.Get=t.Del=t.Put=t.Post=t.Endpoint=t.ApiDescription=void 0;const o=i(2318);t.ApiDescription=e=>(t,i)=>{(0,o.initFieldMetadata)(t,i).description=e};t.Endpoint=e=>(t,i)=>{const n=(0,o.initFieldMetadata)(t,i);n.httpMethod=e.method,n.url=e.url||"/"};const HttpMethodDecoratorFactory=e=>i=>(o,n,r)=>(0,t.Endpoint)({method:e,url:i})(o,n);t.Post=HttpMethodDecoratorFactory(o.HttpMethod.POST),t.Put=HttpMethodDecoratorFactory(o.HttpMethod.PUT),t.Del=HttpMethodDecoratorFactory(o.HttpMethod.DEL),t.Get=HttpMethodDecoratorFactory(o.HttpMethod.GET),t.Head=HttpMethodDecoratorFactory(o.HttpMethod.HEAD);t.ApiResponse=e=>(t,i,n)=>{const r=(0,o.initFieldMetadata)(t,i);e===String?r.responseValidationDto={id:"",primitiveType:o.DataType.STRING,fields:[]}:e===Number?r.responseValidationDto={id:"",primitiveType:o.DataType.NUMBER,fields:[]}:e===Boolean?r.responseValidationDto={id:"",primitiveType:o.DataType.BOOLEAN,fields:[]}:r.responseValidationDto=(0,o.getObjectMetadata)(e)};t.OpenAccess=()=>(e,t)=>{(0,o.initFieldMetadata)(e,t).openAccess=!0};t.TfaRequired=()=>(e,t)=>{(0,o.initFieldMetadata)(e,t).tfaRequired=!0};t.AccessCondition=e=>(t,i)=>{(0,o.initFieldMetadata)(t,i).accessConditions=e};const RequestDeco=e=>(t,i,n)=>{const r=(0,o.initFieldMetadata)(t,i),s=Reflect.getMetadata("design:paramtypes",t,i)||[];switch(e){case"body":r.bodyValidationDto=(0,o.getObjectMetadata)(s[n]);break;case"params":r.paramsValidationDto=(0,o.getObjectMetadata)(s[n]);break;case"queries":r.queriesValidationDto=(0,o.getObjectMetadata)(s[n])}r.params||(r.params={}),r.params[n]={source:e,diClass:s[n]}};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,i)=>{(0,o.initFieldMetadata)(t,i).uriMapper=e};t.CurrentUser=e=>(t,i)=>{const n=(0,o.initFieldMetadata)(t,i);n.userResolver=e,n.serverValue=!0}},6507:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileUploadHandler=void 0;t.AbstractFileUploadHandler=class AbstractFileUploadHandler{}},4839:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FileUploadHandler=void 0;const s=i(2318),a=i(7179),d=i(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([{fromURI:e,toURI:t}])}))}copyFile(e,t){return r(this,void 0,void 0,(function*(){yield this.fileService.copyObject([{fromURI:e,toURI: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(yield this.fileService.getAccessUrls([e],!0))[0]}))}resolvePrivateUrl(e){return r(this,void 0,void 0,(function*(){return(yield this.fileService.getAccessUrls([e],!1))[0]}))}};l=o([(0,s.Injectable)(),n("design:paramtypes",[a.AbstractFileService])],l),t.FileUploadHandler=l},5232:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5048:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRepository=void 0;const n=i(2318);t.AbstractRepository=class AbstractRepository{constructor(e){this.model=e,this.modelMetadata=(0,n.getObjectMetadata)(this.model)}beforeCreating(e,t){return o(this,void 0,void 0,(function*(){for(const i of t)for(const t of this.modelMetadata.fields)t.userResolver&&e&&(i[t.name]=t.userResolver(e))}))}project(e,t){return t?e.map((e=>t.reduce(((t,i)=>Object.assign(t,{[i]:e[i]})),{}))):e}}},9073:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoRepository=t.MultipleMap=t.SingleMap=void 0;const n=i(2318),r=i(5048),s=i(3355);t.SingleMap=(e,t,i,o,n)=>({multiple:!1,modelClass:e,forwardOps:t,forwardMapping:e=>{const t=i(e[0]||{});return t&&[t]},rootMapping:e=>{const t=e&&e[0];return o(t)},nestedMapping:n});t.MultipleMap=(e,t,i,o,n)=>({multiple:!0,modelClass:e,forwardOps:t,forwardMapping:i,rootMapping:o,nestedMapping:n});class DtoRepository extends r.AbstractRepository{constructor(e,t){super(e),this.model=e,this.dissolver=t}getMapValue(e,t,i,r,s){return o(this,void 0,void 0,(function*(){for(const o of i){const i=yield t(o);let a=r?yield r(o,o.forwardMapping(i),i):o.forwardMapping(i);if(o.nestedMapping&&a)for(const i of a)yield this.getMapValue(e,t,o.nestedMapping(i),r,s);s&&(a=yield s(o,o.forwardMapping(i),i));const d=o.rootMapping(a);(0,n.deepMerge)(e,d)}}))}createMany({principal:e,body:t,tx:i}){return o(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=>o(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({ops:e.forwardOps(),queryProvider:i})).records}))),this.dissolver(a),((t,r,a)=>o(this,void 0,void 0,(function*(){if(!r)return[];const o=new s.ModelRepository(t.modelClass),d=t.forwardOps();if(t.multiple){yield o.deleteMany({ops:d,tx:i});return(yield o.createMany({principal:e,body:{records:r},tx:i})).records}{const s=r[0];if(!s)return[];if(0===a.length){return(yield o.createMany({principal:e,body:{records:r},tx:i})).records}if(1===a.length){const t=yield o.updateMany({principal:e,ops:d,body:{update:s},tx:i});return[Object.assign(Object.assign(Object.assign({},a[0]),s),t.modified[0])]}throw n.Errors.VALIDATION_ERROR(`Found multiple record when creating ${t.modelClass.name}`)}})))),r.push(a);return{records:r}}))}updateMany({principal:e,queries:t,ops:i,body:r,tx:a}){var d;return o(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 n.Errors.VALIDATION_ERROR("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=>o(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({ops:e.forwardOps(i),queryProvider:a})).records}))),this.dissolver(l),((t,n,r)=>o(this,void 0,void 0,(function*(){if(!n)return[];const o=new s.ModelRepository(t.modelClass),d=t.forwardOps(i);if(t.multiple){yield o.deleteMany({ops:d,tx:a});return(yield o.createMany({principal:e,body:{records:n},tx:a})).records}{const t=n[0];return t?0==r.length?[]:(r.length>1?(yield o.deleteMany({ops:d,tx:a}),yield o.createMany({principal:e,body:{records:[t]},tx:a})):yield o.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:i}){var r;return o(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 n.Errors.VALIDATION_ERROR("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>o(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),(e=>o(this,void 0,void 0,(function*(){const o=new s.ModelRepository(e.modelClass);return(yield o.getMany({ops:e.forwardOps(t),queryProvider:i})).records})))),a.id?{records:this.project([a],e.projection),total:1}:{records:[],total:0}}))}deleteMany({queries:e,ops:t,tx:i}){var r;return o(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 n.Errors.VALIDATION_ERROR("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>o(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),void 0,(n=>o(this,void 0,void 0,(function*(){const o=new s.ModelRepository(n.modelClass),r=n.forwardOps(t);return(yield o.deleteMany({queries:{returning:null==e?void 0:e.returning},ops:r,tx:i})).modified})))),{modified:a.id?[a]:[]}}))}}t.DtoRepository=DtoRepository},8023:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3355:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelRepository=void 0;const n=i(2318),r=i(7756),s=i(6507),a=i(5048),d=i(2552),l=i(5481);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 i=t.hasMany.relationDto,o=this.getRequestQueryConditionFromQuery(null==e?void 0:e.fields[t.name],Object.assign(Object.assign({},i),{fields:i.fields.filter((e=>{var i;return e.name!==(null===(i=t.hasMany)||void 0===i?void 0:i.column)}))}));return{modelId:t.hasMany.relationDto.id,targetField:t.hasMany.column,queries:o.length?{_and:o}:{}}}))}getUploadHandler(){return o(this,void 0,void 0,(function*(){if(void 0===this.fileUploadHandler){const e=(0,n.getServiceProvider)().getInjector();this.fileUploadHandler=e.resolveOptional(s.AbstractFileUploadHandler)||null,yield e.initInstances()}return this.fileUploadHandler}))}getRequestQueryConditionFromQuery(e,t){var i;const o=[];for(const s of(0,r.getDirectFields)(t)){const r=`${t.id}.${s.name}`,a=e[s.name];if(void 0!==a)if(s.pk||s.fk||s.isSymbol)o.push({_in:{[r]:a}});else if(s.enum)o.push({_in:{[r]:a}});else switch(s.dataType){case n.DataType.STRING:if(s.searchable){const e={[(null==s?void 0:s.searchable.caseSensitive)?(null==s?void 0:s.searchable.accentSensitive)?"_sub":"_usub":(null===(i=null==s?void 0:s.searchable)||void 0===i?void 0:i.accentSensitive)?"_isub":"_iusub"]:{[r]:a}};o.push(e)}else o.push({_eq:{[r]:a}});break;case n.DataType.NUMBER:const e=new n.RangeQueryDto;Object.assign(e,a),e.min&&(e.minExclusive?o.push({_gt:{[r]:e.min}}):o.push({_gte:{[r]:e.min}})),e.max&&(e.maxExclusive?o.push({_lt:{[r]:e.max}}):o.push({_lte:{[r]:e.max}}));break;case n.DataType.BOOLEAN:o.push({_eq:{[r]:a}})}}return o}uriHandling(e){var t,i;return o(this,void 0,void 0,(function*(){const r=[],s=yield this.getUploadHandler(),a=[],uriHandler=(e,t,i,n)=>o(this,void 0,void 0,(function*(){const o=t(e,i);o&&(yield s.copyFile(e,o),n(o))}));if(s)for(const o of this.modelMetadata.fields)for(const s of e)if(o.uriMapper){const e=s[o.name];if(!e)continue;(null===(t=o.mimeProps)||void 0===t?void 0:t.keepOnRemove)||r.push(e),a.push(uriHandler(e,o.uriMapper,(0,n.getSystemLocale)(),(e=>s[o.name]=e)))}else if(o.multiLocaleColumn){const e=this.modelMetadata.fields.find((e=>e.name===o.multiLocaleColumn));if((null==e?void 0:e.uriMapper)&&s[o.name]){const t=Object.keys(s[o.name]).map((e=>[e,s[o.name][e]]));for(const n of t)(null===(i=e.mimeProps)||void 0===i?void 0:i.keepOnRemove)||r.push(n[1]),a.push(uriHandler(n[1],e.uriMapper,n[0],(e=>s[o.name][n[0]]=e)))}}return yield Promise.all(a),()=>o(this,void 0,void 0,(function*(){s&&(yield Promise.all(r.map((e=>s.removeFile(e)))))}))}))}beforeReturning(e){return o(this,void 0,void 0,(function*(){const t=yield this.getUploadHandler();if(!t)return;const i=[];for(const n of e)for(const e of this.modelMetadata.fields)if(e.uriMapper){if(!n[e.name])continue;i.push((()=>o(this,void 0,void 0,(function*(){var i;n[e.name]=(null===(i=e.mimeProps)||void 0===i?void 0:i.public)?yield t.resolvePublicUrl(n[e.name]):yield t.resolvePrivateUrl(n[e.name])})))())}else if(e.multiLocaleColumn){const r=this.modelMetadata.fields.find((t=>t.name===e.multiLocaleColumn));if(null==r?void 0:r.uriMapper){const s=n[e.name];if(!s)continue;for(const e of Object.keys(s))i.push((()=>o(this,void 0,void 0,(function*(){var i;s[e]=(null===(i=r.mimeProps)||void 0===i?void 0:i.public)?yield t.resolvePublicUrl(s[e]):yield t.resolvePrivateUrl(s[e])})))())}}yield Promise.all(i)}))}createMany({principal:e,body:t,tx:i}){var s;return o(this,void 0,void 0,(function*(){const o=t.records;if(!o.length)return{records:[]};const a=(0,r.getDirectFields)(this.modelMetadata),c=a.filter((e=>!!e.multiLocaleColumn)),u=yield this.uriHandling(o),p=(0,n.getSystemLocale)();if(p)for(const e of o)for(const t of c)e[t.name]&&(e[t.multiLocaleColumn]=e[t.name][p]);const h=o.map(((e,t)=>c.filter((t=>!!e[t.name])).map((e=>({recordIndex:t,field:e.name,entryObject:{}}))))).flatMap((e=>e)),f=yield i.use(l.LocaleEntry).createMany(h.map((e=>e.entryObject))),v=o.map((e=>c.filter((t=>!!e[t.name])).map((t=>e[t.name])))).flatMap((e=>e)).map(((e,t)=>Object.keys(e).map((i=>({localeCode:i,entryId:f[t].id,translation:e[i]}))))).flatMap((e=>e));yield i.use(d.LocaleTranslation).createMany(v),t.records=o.map(((e,t)=>a.reduce(((i,o)=>{let n=e[o.name];if(o.multiLocaleColumn){const e=h.findIndex((e=>e.recordIndex===t&&e.field===o.name));e>=0&&(n=f[e].id)}return Object.assign(i,void 0!==n?{[o.name]:n}:{})}),{}))),yield this.beforeCreating(e,t.records);let y=t.records.length?yield i.use(this.model).createMany(t.records):[];yield this.beforeReturning(y);const g=this.modelMetadata.fields.filter((e=>!e.multiLocaleColumn&&(e.pk||e.serverValue||e.mimeProps))).map((e=>e.name));y=this.project(y,g);const m=this.modelMetadata.fields.filter((e=>!!e.hasMany));for(const r of m){const a=y.flatMap(((e,t)=>{var i;const n=o[t][r.name];return n?((null===(i=r.hasMany)||void 0===i?void 0:i.single)?[n]:n).map((t=>Object.assign(Object.assign({},t),{[r.hasMany.column]:e.id}))):[]}));if(a.length){const o=new ModelRepository((0,n.getModelById)(r.hasMany.relationDto.id));t.records=a;const d=yield o.createMany({principal:e,body:t,tx:i});for(let e=0;e<d.records.length;e++)a[e]=Object.assign(Object.assign({},a[e]),d.records[e]);for(let e=0;e<y.length;e++){const t=[];for(let i=0;i<a.length;i++)a[i][r.hasMany.column]===y[e].id&&t.push(d.records[i]);y[e]=Object.assign(Object.assign({},y[e]),{[r.name]:(null===(s=r.hasMany)||void 0===s?void 0:s.single)?t[0]:t})}}}return yield u(),{records:y}}))}updateMany({principal:e,ops:t,queries:i,body:s,tx:a}){var c,u;return o(this,void 0,void 0,(function*(){const o=t||[],p=this.modelMetadata.fields.filter((e=>!!e.hasMany)),h=(0,n.getSystemLocale)(),f=(0,r.getDirectFields)(this.modelMetadata).filter((e=>!e.multiLocaleColumn&&(void 0!==s.update[e.name]||e.isMultiLocale&&!!h))),v=Object.keys(s.update),y=this.modelMetadata.fields.filter((e=>v.includes(e.name)&&e.multiLocaleColumn)),g=yield this.uriHandling([s.update]),m=(0,n.leanData)(f.reduce(((e,t)=>Object.assign(e,{[t.name]:s.update[t.name]})),{}))||{};if(h)for(const e of y)if(s.update[e.name]){const t=s.update[e.name][h];void 0!==t&&(m[e.multiLocaleColumn]=t)}if(null==i?void 0:i.fields){const e=this.getRequestQueryConditionFromQuery(i.fields,this.modelMetadata);e.length&&o.push(...e)}const b=o.length?{_and:[...o]}:{},M=this.getNestedQueries(i);let S=[],R=[];if(M.length){const e=yield a.use(this.model).getMany(b,{projection:["id"]},M);S=e.records.map((e=>e.id)),S.length&&(R=f.length?yield a.use(this.model).updateMany({_in:{id:S}},m,!0):S.map((e=>({id:e}))))}else if(f.length)R=yield a.use(this.model).updateMany(b,m,!0),S=R.map((e=>e.id));else{const e=yield a.use(this.model).getMany(b,{projection:["id"]});S=e.records.map((e=>e.id)),R=S.map((e=>({id:e})))}const j=R.map((e=>Object.assign(Object.assign({},s.update),e)));if(y.length){const e=yield a.use(this.model).getRecords({_in:{id:S}},{projection:["id",...y.map((e=>e.name))]}),t=e.map((e=>y.filter((t=>!e[t.name])).map((t=>({recordId:e.id,field:t.name}))))).flatMap((e=>e)),i=t.length?yield a.use(l.LocaleEntry).createMany(t.map((()=>({})))):[],o=[];i.forEach(((i,n)=>{const r=t[n],s=e.find((e=>e.id===r.recordId));if(s){s[r.field]=i.id;let e=o.find((e=>e.id===s.id));e||(e={id:s.id},o.push(e)),e[r.field]=i.id}})),yield Promise.all(o.map((e=>a.use(this.model).updateById(e.id,(0,n.omitData)(e,["id"])))));const r=[];for(const t of y){const i=s.update[t.name],o=Object.keys(i||{}).filter((e=>e!==h));o.length&&r.push(...e.map((e=>o.map((o=>({entryId:e[t.name],langCode:o,translation:i[o]}))))).flatMap((e=>e)))}r.length&&(yield a.use(d.LocaleTranslation).deleteMany({_or:r.map((e=>({_eq:{entryId:e.entryId,localeCode:e.langCode}})))}),yield a.use(d.LocaleTranslation).createMany(r.map((e=>({entryId:e.entryId,localeCode:e.langCode,translation:e.translation})))))}for(const t of p){const i=s.update[t.name];if(void 0===i||!S.length)continue;if(S.length>1)throw n.Errors.SYSTEM_ERROR(`Multiple records found while updating @HasMany field: ${t.name}`);const o=j.find((e=>e.id===S[0])),r=(0,n.getModelById)(t.hasMany.relationDto.id),d=a.use(r),l=(yield d.getRecords({_eq:{[t.hasMany.column]:o.id}},{limit:(null===(c=t.hasMany)||void 0===c?void 0:c.single)?1:void 0})).map((e=>e.id)),p=i.map((e=>e.id)).filter((e=>!!e)),h=l.filter((e=>!p.includes(e))),f=i.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasMany.column]:o.id}))),v=i.filter((e=>!!e.id));h.length&&(yield d.deleteMany({_in:{id:h}}));const y=new ModelRepository(r),g=yield y.createMany({principal:e,body:{records:f},tx:a}),m=yield Promise.all(v.filter((e=>Object.keys(e).length>1)).map((t=>y.updateMany({queries:{returning:!0},principal:e,ops:[{_eq:{id:t.id}}],tx:a,body:{update:(0,n.leanData)(Object.assign(Object.assign({},t),{id:void 0}))}})))),b=f.map(((e,t)=>Object.assign(Object.assign({},e),g.records[t]))).concat(m.map((e=>e.modified[0])));o[t.name]=(null===(u=t.hasMany)||void 0===u?void 0:u.single)?b[0]:b}let C=["id"];return(null==i?void 0:i.returning)&&(C=[...C,...Object.keys(s.update).filter((e=>void 0!==s.update[e])),"lastModified"]),yield g(),yield this.beforeReturning(j),{modified:this.project(j,C)}}))}getMany({queries:e,ops:t,queryProvider:i}){var r;return o(this,void 0,void 0,(function*(){const o=t||[];if((null==e?void 0:e.fields)&&o.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&&o.push({_or:t})}const s=this.modelMetadata.fields.filter((t=>t.isMultiLocale&&(!(null==e?void 0:e.projection)||e.projection.includes(t.name)))),a=this.modelMetadata.fields.filter((e=>s.find((t=>t.name===e.multiLocaleColumn)))),l=(null==e?void 0:e.projection)&&[...e.projection.filter((e=>!this.modelMetadata.fields.find((t=>t.name===e&&!!t.hasMany)))),...a.map((e=>e.name))],c=yield i.use(this.model).getMany(o.length?{_and:o}:{},{limit:null==e?void 0:e.limit,page:null==e?void 0:e.page,projection:l,order:"random"===(null==e?void 0:e.order)?e.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)),u=c.records.map((e=>e.id)),p=c.records.map((e=>a.map((t=>e[t.name])))).flatMap((e=>e)).filter((e=>e)),h=(0,n.getSystemLocale)(),f=p.length?(null==e?void 0:e.locale)?e.locale.toLowerCase()!==h?yield i.use(d.LocaleTranslation).getRecords({_in:{entryId:p},_eq:{localeCode:e.locale}},{projection:["entryId","localeCode","translation"]}):[]:yield i.use(d.LocaleTranslation).getRecords({_in:{entryId:p}},{projection:["entryId","localeCode","translation"]}):[];for(const t of c.records)for(const i of a)if(null==e?void 0:e.locale){const o=f.find((o=>o.localeCode===e.locale&&o.entryId===t[i.name]));o&&(t[i.multiLocaleColumn]=o.translation)}else{const e=f.filter((e=>e.entryId===t[i.name]));e.length?t[i.name]=e.reduce(((e,t)=>Object.assign(e,{[t.localeCode]:t.translation})),{}):t[i.name]={}}for(const t of this.modelMetadata.fields){if(!t.hasMany||(null==e?void 0:e.projection)&&!e.projection.includes(t.name))continue;const o=(0,n.getModelById)(t.hasMany.relationDto.id),r=new ModelRepository(o),s=u.length?yield r.getMany({queries:{fields:{[t.hasMany.column]:u},limit:t.hasMany.single?1:0},queryProvider:i}):{records:[]};for(const e of c.records){const i=s.records.filter((i=>i[t.hasMany.column]===e.id));e[t.name]=t.hasMany.single?i[0]:i}}return yield this.beforeReturning(c.records),{total:c.total,records:this.project(c.records,(null==e?void 0:e.projection)&&[...e.projection,...e.locale?[]:l||[]].reduce(n.uniqueReducer,[]))}}))}deleteMany({queries:e,ops:t,tx:i}){var n,r;return o(this,void 0,void 0,(function*(){let o=t||[];if(null==e?void 0:e.fields){const t=this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata);t.length&&o.push(...t)}const s=o.length?{_and:[...o,...t||[]]}:{},a=this.getNestedQueries(e);let c=[];const u=this.modelMetadata.fields.filter((e=>e.uriMapper)),p=this.modelMetadata.fields.filter((e=>e.multiLocaleColumn));if(a.length||p.length||u.length){const e=yield i.use(this.model).getRecords(s,{projection:["id",...[...p,...u].map((e=>e.name))]},a);yield i.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}});const t=[];for(const i of e)for(const e of u)i[e.name]&&!(null===(n=e.mimeProps)||void 0===n?void 0:n.keepOnRemove)&&t.push(i[e.name]);const o=[];for(const t of e)for(const e of p){const i=this.modelMetadata.fields.find((t=>t.name===e.name));(null==i?void 0:i.uriMapper)&&!(null===(r=i.mimeProps)||void 0===r?void 0:r.keepOnRemove)&&t[i.name]&&o.push(t[i.name])}if(o.length){const e=yield i.use(d.LocaleTranslation).getRecords({_in:{entryId:o}},{projection:["translation"]});for(const i of e)i.translation&&t.push(i.translation)}const h=e.map((e=>p.map((t=>e[t.name])))).flatMap((e=>e)).filter((e=>!!e));if(h.length&&(yield i.use(l.LocaleEntry).deleteMany({_in:{id:h}})),t.length){const e=yield this.getUploadHandler();e&&(yield Promise.all(t.map((t=>e.removeFile(t)))))}c=e}else c=yield i.use(this.model).deleteMany(s,null==e?void 0:e.returning);return{modified:c}}))}}t.ModelRepository=ModelRepository},2255:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractAccessCondition=void 0;t.AbstractAccessCondition=class AbstractAccessCondition{}},1071:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FilterModelFieldAccessCondition=void 0;const r=i(2318),s=i(2255);t.FilterModelFieldAccessCondition=(e,t,i)=>{let a=class _ extends s.AbstractAccessCondition{resolveConditionValue(e){return n(this,void 0,void 0,(function*(){return i(e)}))}getConditionMetadata(){return{name:t,valueType:r.AccessConditionValueType.CHOICES,valueConstraint:(0,r.getObjectMetadata)(e).fields.map((e=>e.name))}}validate(e,t){return n(this,void 0,void 0,(function*(){return!!e&&e.every((e=>t.includes(e)))}))}};return a=o([(0,r.Register)()],a),a}},3198:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.MaximumQueryLimit=void 0;const r=i(2318),s=i(2255);let a=class MaximumQueryLimit extends s.AbstractAccessCondition{resolveConditionValue(e){return n(this,void 0,void 0,(function*(){let t=e.getQuery().limit;return t&&(t=parseInt(t)),t||0}))}validate(e,t){return n(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=o([(0,r.Register)()],a),t.MaximumQueryLimit=a},7493:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},9202:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.getApiInfo=t.getEndpointId=void 0;const n=i(2318),r=i(767),s=i(5530);t.getEndpointId=e=>`${e.httpMethod}:${e.mount}`;t.getApiInfo=()=>o(void 0,void 0,void 0,(function*(){const e=(0,n.getServiceProvider)().getInjector(),i=e.resolveOptional(r.AbstractHttpRequestHandler),o=e.resolveOptional(s.AbstractServerSocketManager);yield e.initInstances();return{permissions:[...i?yield i.getMountedEndpointInfo():[],...o?yield o.getMountedEndpointInfo():[]].map((i=>{var o;return{id:(0,t.getEndpointId)(i.endpoint),description:i.endpointMetadata.description,name:i.endpointMetadata.displayName||i.endpointMetadata.name,openAccess:!!i.endpointMetadata.openAccess,permissionGroup:i.endpointMetadata.permissionGroup||"",accessConditions:(null===(o=i.endpointMetadata.accessConditions)||void 0===o?void 0:o.map((t=>e.resolve(t).getConditionMetadata())))||[],readOnly:i.endpointMetadata.httpMethod===n.HttpMethod.GET,tfaRequired:!!i.endpointMetadata.tfaRequired,method:i.endpointMetadata.httpMethod,mount:i.endpoint.mount||"",paramDto:i.endpointMetadata.paramsValidationDto,queryDto:i.endpointMetadata.queriesValidationDto,bodyDto:i.endpointMetadata.bodyValidationDto,responseDto:i.endpointMetadata.responseValidationDto}}))}}))},341:function(e,t,i){var o=this&&this.__createBinding||(Object.create?function(e,t,i,o){void 0===o&&(o=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,o,n)}:function(e,t,i,o){void 0===o&&(o=i),e[o]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||o(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),n(i(9025),t),n(i(4638),t),n(i(1820),t),n(i(1870),t),n(i(4972),t),n(i(4435),t),n(i(7540),t),n(i(8985),t),n(i(2872),t),n(i(7678),t),n(i(8903),t),n(i(2417),t),n(i(1532),t),n(i(5879),t),n(i(6004),t),n(i(7282),t),n(i(767),t),n(i(225),t),n(i(7493),t),n(i(2255),t),n(i(1071),t),n(i(3198),t),n(i(5709),t),n(i(3355),t),n(i(9073),t),n(i(8023),t),n(i(5048),t),n(i(5530),t),n(i(2841),t),n(i(7152),t),n(i(8577),t),n(i(2665),t),n(i(9990),t),n(i(9202),t),n(i(6507),t),n(i(4839),t),n(i(5232),t),n(i(5572),t),n(i(10),t),n(i(5481),t),n(i(2552),t),n(i(889),t),n(i(5537),t),n(i(226),t),n(i(8836),t),n(i(9627),t),n(i(7014),t),n(i(7179),t),n(i(4487),t),n(i(7120),t),n(i(4),t),n(i(6135),t),n(i(4),t),n(i(5991),t),n(i(3912),t),n(i(6135),t),n(i(1786),t),n(i(7380),t),n(i(8037),t),n(i(2345),t),n(i(7724),t),n(i(1556),t),n(i(2363),t),n(i(4683),t),n(i(9527),t),n(i(3376),t),n(i(5033),t),n(i(523),t)},4683:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobController=void 0;const o=i(2318),n=i(5007);class AbstractJobController extends n.Transactionable{getAllJobs(){const e=(0,o.getObjectMetadata)(this.constructor);return(null==e?void 0:e.jobs)||[]}}t.AbstractJobController=AbstractJobController},523:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobRepository=void 0;t.AbstractJobRepository=class AbstractJobRepository{}},9527:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobScheduler=void 0;const n=i(2318),r=i(4683);t.AbstractJobScheduler=class AbstractJobScheduler{constructor(e){this.logger=e,this._jobs=null}getAvailableJobInfo(){return o(this,void 0,void 0,(function*(){if(null===this._jobs){const e=(0,n.getServiceProvider)().getInjector(),t=e.resolveMultiple(r.AbstractJobController);yield e.initInstances(),this._jobs=t.flatMap((e=>e.getAllJobs().map((t=>Object.assign(Object.assign({},t),{handlerFn:e[t.handlerName].bind(e)})))))}return this._jobs}))}scheduleJobAt(e){return this.scheduleJob(e)}executeJob(e){return o(this,void 0,void 0,(function*(){const t=(yield this.getAvailableJobInfo()).find((t=>t.jobName===e.jobName));t&&(yield t.handlerFn(...e.params||[])),t&&!e.at||(yield this.removeJob(e.jobId),this.logger.info(t?`Remove one-time job ${e.jobName} at timestamp ${e.at}`:`Remove not found job: ${e.jobName}`))}))}}},3376:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsJobScheduler=void 0;const a=i(2318),d=i(9336),l=s(i(1495)),c=i(9527),u=i(2363),gcdBetween=(e,t)=>{const i=e>t?e:t,o=e>t?t:e;if(i<=0||o<=0)return 1;if(i%o==0)return o;{const e=Math.trunc(i/o);return gcdBetween(o,i-o*e)}},gcdOf=(e,t)=>t.length?gcdOf(gcdBetween(e,t[0]),t.slice(1)):e,getWaitExpression=e=>`Wait ${e} seconds`;let p=class AwsJobScheduler extends c.AbstractJobScheduler{constructor(e,t,i,o,n,r,s="default",a="claire-aws-job-",l="one-minute-step-function-trigger"){super(e),this.logger=e,this.redisClient=t,this.uniqueIdKey=i,this.apiLambdaFunctionArn=o,this.stepFunctionName=n,this.iamRoleArn=r,this.eventBusName=s,this.jobNamePrefix=a,this.oneMinuteRule=l,this.eventbridge=new d.EventBridge,this.stepfunctions=new d.StepFunctions({apiVersion:"2016-11-23"})}handleInterval(e){return r(this,void 0,void 0,(function*(){this.logger.debug("Handle interval",e,typeof e);const t=(yield this.getAvailableJobInfo()).filter((t=>t.interval&&e%t.interval==0));yield Promise.all(t.map((e=>this.executeJob(Object.assign(Object.assign({},e),{jobId:e.jobName})))))}))}handleCron(e){return r(this,void 0,void 0,(function*(){this.logger.debug("Handle cron",e),yield this.executeJob(e)}))}generateCronFromTimestamp(e){const t=new Date(e);return[t.getUTCMinutes(),t.getUTCHours(),t.getUTCDate(),t.getUTCMonth(),"?",t.getUTCFullYear()].join(" ")}isActiveScheduler(){return!1}getAllScheduledJobs(){return r(this,void 0,void 0,(function*(){const e=yield this.getAvailableJobInfo(),t=yield this.eventbridge.listRules({EventBusName:this.eventBusName,NamePrefix:this.jobNamePrefix}).promise();return(yield Promise.all((t.Rules||[]).map((e=>r(this,void 0,void 0,(function*(){var t;const i=e.Name,o=null===(t=(yield this.eventbridge.listTargetsByRule({EventBusName:this.eventBusName,Rule:i}).promise()).Targets)||void 0===t?void 0:t.find((e=>e.Id===i));if(!o||!o.Input)return;return JSON.parse(o.Input).requestContext.cronScheduler.data})))))).filter((e=>!!e)).concat(e.filter((e=>e.interval)).map((e=>Object.assign(Object.assign({},e),{jobId:e.jobName}))))}))}scheduleJob(e){return r(this,void 0,void 0,(function*(){if(this.logger.debug("Scheduling job: ",e),e.cron||e.at){const t=yield this.redisClient.incr(this.uniqueIdKey),i=`${this.jobNamePrefix}${t}`,o=e.cron?`${e.cron} *`:this.generateCronFromTimestamp(e.at);return this.logger.debug("Cron expression",o),yield this.eventbridge.putRule({Name:i,Description:`${e.jobName} - ${e.cron||e.at}`,EventBusName:this.eventBusName,ScheduleExpression:`cron(${o})`,State:"ENABLED"}).promise(),yield this.eventbridge.putTargets({Rule:i,Targets:[{Arn:this.apiLambdaFunctionArn,Id:i,Input:JSON.stringify({requestContext:{cronScheduler:{data:Object.assign(Object.assign({},e),{jobId:i})}}})}]}).promise(),i}if(e.interval)return e.jobName;throw a.Errors.SYSTEM_ERROR(`Job does not have time config: ${e.jobName}`)}))}syncJobs(){return r(this,void 0,void 0,(function*(){this.logger.debug("Checking interval scheduler"),yield this.checkIntervalScheduler();const e=yield this.getAllScheduledJobs(),t=yield this.getAvailableJobInfo(),i=e.filter((e=>!t.find((t=>t.jobName===e.jobName))));for(const e of i)this.logger.info(`Removing stale job: ${e.jobName} of id: ${e.jobId}`),yield this.removeJob(e.jobId);i.length&&this.logger.info(`Cleaned up: ${i.length} stale jobs`),this.logger.debug("Remove scheduled cron jobs");const o=e.filter((e=>e.cron));yield Promise.all(o.map((e=>this.removeJob(e.jobId))));const n=t.filter((e=>e.cron||e.interval));this.logger.debug("Scheduling cron & interval jobs");for(const e of n)yield this.scheduleJob({jobName:e.jobName,cron:e.cron,interval:e.interval})}))}removeJob(e){return r(this,void 0,void 0,(function*(){yield this.eventbridge.removeTargets({EventBusName:this.eventBusName,Rule:e,Ids:[e]}).promise(),yield this.eventbridge.deleteRule({EventBusName:this.eventBusName,Name:e}).promise()}))}checkIntervalScheduler(){var e,t;return r(this,void 0,void 0,(function*(){const i=(yield this.getAvailableJobInfo()).filter((e=>e.interval)),o=i.map((e=>e.interval)),[n,r]=((e,t)=>{let i=u.JobInterval.EVERY_30S;t.length&&(i=gcdOf(t[0],t.slice(1)),i<u.JobInterval.EVERY_5S&&(i=u.JobInterval.EVERY_5S));const o=Math.trunc(60/i),n=[];for(let e=0;e<o;e++)n.push(e*i);return[i,`\n {\n "StartAt": "Create items",\n "States": {\n "Create items": {\n "Type": "Pass",\n "Next": "Loop",\n "Result": ${JSON.stringify(n)}\n },\n "Loop": {\n "Type": "Map",\n "End": true,\n "Iterator": {\n "StartAt": "${getWaitExpression(i)}",\n "States": {\n "${getWaitExpression(i)}": {\n "Type": "Wait",\n "Seconds": ${i},\n "Next": "Convert time to request object"\n },\n "Convert time to request object": {\n "Type": "Pass",\n "Next": "Lambda Invoke",\n "Result": {\n "requestContext": {\n "intervalScheduler": {\n "time": "$"\n }\n }\n }\n },\n "Lambda Invoke": {\n "Type": "Task",\n "Resource": "arn:aws:states:::lambda:invoke",\n "Parameters": {\n "Payload.$": "$",\n "FunctionName": "${e}:$LATEST"\n },\n "End": true,\n "OutputPath": "$.Payload"\n }\n }\n },\n "MaxConcurrency": 1\n }\n },\n "Comment": "One minute loop to trigger lambda function"\n }\n `]})(this.apiLambdaFunctionArn,o);this.logger.debug("Listing all state machines");const s=yield this.stepfunctions.listStateMachines({}).promise();let a=null===(e=s.stateMachines.find((e=>e.name.includes(this.stepFunctionName))))||void 0===e?void 0:e.stateMachineArn,d=a;if(a){(yield this.stepfunctions.describeStateMachine({stateMachineArn:a}).promise()).definition.includes(getWaitExpression(n))||(this.logger.debug("Step function definition changed, create new state machine"),d="")}const l=`${this.stepFunctionName}-${n}`;if(!d){this.logger.debug(`Create new step function with interval ${n} seconds`);d=(yield this.stepfunctions.createStateMachine({definition:r,name:l,roleArn:this.iamRoleArn,type:"EXPRESS"}).promise()).stateMachineArn}this.logger.debug("Step function ARNs old / new",a,d),this.logger.debug("Getting one minute rule");const c=yield this.eventbridge.listRules({EventBusName:this.eventBusName,NamePrefix:this.oneMinuteRule}).promise(),p=null===(t=c.Rules)||void 0===t?void 0:t.find((e=>e.Name==this.oneMinuteRule));p||(this.logger.debug("Create new one minute rule"),yield this.eventbridge.putRule({EventBusName:this.eventBusName,Name:this.oneMinuteRule,Description:"One minute trigger function for step function",ScheduleExpression:"rate(1 minute)",State:"ENABLED"}).promise()),this.logger.debug("Adding step function state machine as target"),d!==a&&(a&&(this.logger.debug("Removing old target",a),yield this.eventbridge.removeTargets({EventBusName:this.eventBusName,Rule:this.oneMinuteRule,Ids:[this.stepFunctionName]}).promise(),this.logger.debug("Removing old state machine function"),yield this.stepfunctions.deleteStateMachine({stateMachineArn:a}).promise()),this.logger.debug("Adding new target",d),yield this.eventbridge.putTargets({Rule:this.oneMinuteRule,Targets:[{Arn:d,Id:this.stepFunctionName,RoleArn:this.iamRoleArn}]}).promise()),!i.length&&(null==p?void 0:p.State)?(this.logger.info("No interval job found, disable one minute rule"),yield this.eventbridge.disableRule({EventBusName:this.eventBusName,Name:this.oneMinuteRule}).promise()):(this.logger.info("Interval job found, enable one minute rule"),yield this.eventbridge.enableRule({EventBusName:this.eventBusName,Name:this.oneMinuteRule}).promise())}))}};p=o([(0,a.LogContext)(),n("design:paramtypes",[a.AbstractLogger,l.default,String,String,String,String,Object,Object,Object])],p),t.AwsJobScheduler=p},5033:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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=i(2318),d=s(i(1495)),l=s(i(9896)),c=s(i(7344)),u=i(9527),p=i(523),h=i(9512);var f;!function(e){e.SCHEDULE_JOB="SCHEDULE_JOB",e.REMOVE_JOB="REMOVE_JOB",e.SYNC_JOB="SYNC_JOB",e.NOTIFY="NOTIFY"}(f||(f={}));let v=class LocalJobScheduler extends u.AbstractJobScheduler{constructor(e,t,i,o,n,r,s,a,d=30){super(e),this.logger=e,this.redisClient=t,this.subscribeClient=i,this.jobRepo=o,this.lockMutexKey=n,this.holdMutexKey=r,this.uniqueIdKey=s,this.multiClientChannel=a,this.keyRetentionDurationSecond=d,this.intervals=[],this.isActive=!1,this.notifyResolver={},this.jobHolder={}}sendJob(e,t,i){this.subscribeClient.publish(this.multiClientChannel,JSON.stringify({type:e,messageId:t,data:i}))}processMessage(e,t,i){return r(this,void 0,void 0,(function*(){switch(e){case f.SYNC_JOB:yield this.syncJobs(),this.sendJob(f.NOTIFY,t);break;case f.NOTIFY:const o=this.notifyResolver[t];if(!o)return;o(i);break;case f.SCHEDULE_JOB:if(!this.isActive)return;const n=i,r=yield this.scheduleJobAt(n);this.sendJob(f.NOTIFY,t,r);break;case f.REMOVE_JOB:if(!this.isActive)return;const s=i;yield this.removeJob(s),this.sendJob(f.NOTIFY,t);break;default:this.logger.error(`Not recognize message type ${e}`)}}))}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"))}))}init(){return r(this,void 0,void 0,(function*(){this.logger.debug("LocalJobScheduler init"),this.logger.debug("Listening on multi client channel"),this.redisClient.on("message",((e,t)=>{if(e===this.multiClientChannel){const e=JSON.parse(t);this.processMessage(e.type,e.messageId,e.data).catch((t=>this.logger.error(`Fail to process message, ${e}`,t)))}})),yield this.subscribeClient.subscribe(this.multiClientChannel),this.logger.debug("Try to claim active scheduler");const e=new l.default([this.redisClient]);try{const t=yield e.acquire([this.lockMutexKey],this.keyRetentionDurationSecond);this.isActive=!0,yield this.extendMutexKey(),yield t.release(),this.logger.debug("Being active scheduler"),this.mutexHoldInterval=setInterval((()=>{this.extendMutexKey()}),Math.trunc(1e3*this.keyRetentionDurationSecond/2)+1)}catch(e){this.logger.info("Failed to lock mutex key, ignore",e)}}))}exit(){this.mutexHoldInterval&&(0,h.clearInterval)(this.mutexHoldInterval),this.redisClient.quit(),this.subscribeClient.quit();for(const e of this.intervals)(0,h.clearInterval)(e);this.logger.debug("LocalJobScheduler exit")}isActiveScheduler(){return this.isActive}getAllScheduledJobs(){return r(this,void 0,void 0,(function*(){return Object.values(this.jobHolder).filter((e=>!!(null==e?void 0:e.jobInfo))).map((e=>null==e?void 0:e.jobInfo))}))}syncJobs(){return r(this,void 0,void 0,(function*(){if(!this.isActive){const e=yield this.redisClient.incr(this.uniqueIdKey);return new Promise((t=>{this.notifyResolver[e]=t,this.sendJob(f.SYNC_JOB,e)}))}{const e=yield this.getAvailableJobInfo();for(const t of e)(t.cron||t.interval)&&(yield this.scheduleJob(t));const t=yield this.jobRepo.getJobs();for(const e of t)yield this.scheduleJob(e)}}))}scheduleJob(e){return r(this,void 0,void 0,(function*(){if(this.isActive){if(e.at){const t=yield this.jobRepo.saveJob({jobName:e.jobName,params:e.params,at:e.at}),i=Object.assign(Object.assign({},e),{jobId:t}),o=setTimeout((()=>{this.executeJob(i).catch((e=>this.logger.error(`Error execute job ${i.jobName} with id: ${i.jobId}`,e)))}),new Date(e.at).getTime()-Date.now());return this.jobHolder[t]={jobCanceler:()=>(0,h.clearTimeout)(o),jobInfo:Object.assign(Object.assign({},e),{jobId:t})},t}if(e.interval){const t=e.jobName,i=Object.assign(Object.assign({},e),{jobId:t}),o=setInterval((()=>{this.executeJob(i).catch((e=>this.logger.error(`Error execute job ${i.jobName} with id: ${i.jobId}`,e)))}),e.interval);return this.jobHolder[t]={jobCanceler:()=>(0,h.clearInterval)(o),jobInfo:Object.assign(Object.assign({},e),{jobId:t})},t}if(e.cron){const t=e.jobName,i=Object.assign(Object.assign({},e),{jobId:t}),o=c.default.scheduleJob(e.cron,(()=>{this.executeJob(i).catch((e=>this.logger.error(`Error execute job ${i.jobName} with id: ${i.jobId}`,e)))}));return this.jobHolder[t]={jobCanceler:()=>o.cancel(),jobInfo:Object.assign(Object.assign({},e),{jobId:t})},t}throw a.Errors.SYSTEM_ERROR(`Job does not have time config: ${e.jobName}`)}{const t=yield this.redisClient.incr(this.uniqueIdKey);return new Promise((i=>{this.notifyResolver[t]=i,this.sendJob(f.SCHEDULE_JOB,t,e)}))}}))}removeJob(e){return r(this,void 0,void 0,(function*(){if(this.isActive){const t=this.jobHolder[e];return t&&(t.jobCanceler(),this.jobHolder[e]=void 0),void(yield this.jobRepo.removeJobById(e))}{const t=yield this.redisClient.incr(this.uniqueIdKey);return new Promise((i=>{this.notifyResolver[t]=i,this.sendJob(f.REMOVE_JOB,t,e)}))}}))}};v=o([(0,a.LogContext)(),n("design:paramtypes",[a.AbstractLogger,d.default,d.default,p.AbstractJobRepository,String,String,String,String,Number])],v),t.LocalJobScheduler=v},1556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CustomJob=t.CronJob=t.IntervalJob=void 0;const o=i(2318);t.IntervalJob=(e,t)=>(i,n)=>{const r=(0,o.initObjectMetadata)(i);r.jobs||(r.jobs=[]),r.jobs.push({jobName:e,interval:t,handlerName:n})};t.CronJob=(e,t)=>(i,n)=>{const r=(0,o.initObjectMetadata)(i);if(r.jobs||(r.jobs=[]),5!==t.split(" ").length)throw o.Errors.SYSTEM_ERROR("Invalid cron expression, expect minute / hour / day / month / day-of-week");r.jobs.push({jobName:e,cron:t,handlerName:n})};t.CustomJob=e=>(t,i)=>{const n=(0,o.initObjectMetadata)(t);n.jobs||(n.jobs=[]),n.jobs.push({jobName:e,handlerName:i})}},2363:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JobInterval=t.CRON_REQUEST_METHOD=t.INTERVAL_REQUEST_METHOD=void 0,t.INTERVAL_REQUEST_METHOD="interval",t.CRON_REQUEST_METHOD="cron",function(e){e[e.EVERY_5S=5]="EVERY_5S",e[e.EVERY_10S=10]="EVERY_10S",e[e.EVERY_15S=15]="EVERY_15S",e[e.EVERY_20S=20]="EVERY_20S",e[e.EVERY_30S=30]="EVERY_30S"}(t.JobInterval||(t.JobInterval={}))},5572:function(e,t,i){var o,n=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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(i(7147)),l=a(i(1017)),c=i(2318);let u=o=class FileLogMedium{constructor(e){const t=e.separated?o.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 i=this.separated?this.destination[o.levels.indexOf(e)]:0;d.default.appendFileSync(i,t)}};u.levels=Object.values(c.LogLevel),u=o=n([(0,c.Initable)(),r("design:paramtypes",[Object])],u),t.FileLogMedium=u},7179:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileService=void 0;const n=i(9025),delay=e=>new Promise((t=>setTimeout(t,e)));t.AbstractFileService=class AbstractFileService{getUploadUrlForTempUri(e){return o(this,void 0,void 0,(function*(){const getPutUrl=()=>o(this,void 0,void 0,(function*(){return(yield this.getPresignedUrl(n.FileOperation.PUT,[e]))[0]})),getDeleteUrl=()=>o(this,void 0,void 0,(function*(){return(yield this.getPresignedUrl(n.FileOperation.DELETE,[e]))[0]}));let t={objectKey:e,putPresignedUrl:yield getPutUrl(),deletePresignedUrl:yield getDeleteUrl()};for(;t.putPresignedUrl.endsWith("/");)yield delay(1e3),t.putPresignedUrl=yield getPutUrl();for(;t.deletePresignedUrl.endsWith("/");)yield delay(1e3),t.deletePresignedUrl=yield getDeleteUrl();return t}))}}},4487:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractMailService=void 0;t.AbstractMailService=class AbstractMailService{}},7014:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractService=void 0;const o=i(5007);class AbstractService extends o.Transactionable{}t.AbstractService=AbstractService},7120:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSmsService=void 0;t.AbstractSmsService=class AbstractSmsService{}},4:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalFileService=void 0;const r=n(i(2167)),s=i(9025),a=i(7179);class LocalFileService extends a.AbstractFileService{constructor(e){super(),this.fileServerUrl=e}getFileSize(e){return o(this,void 0,void 0,(function*(){return Promise.all(e.map((e=>o(this,void 0,void 0,(function*(){var t;return(null===(t=(yield r.default.head(`${this.fileServerUrl}/info?objectKey="/${e}"`)).data)||void 0===t?void 0:t.size)||0})))))}))}getAccessUrls(e,t){return o(this,void 0,void 0,(function*(){return e.map((e=>`${this.fileServerUrl}/${e}`))}))}getPresignedUrl(e,t){return o(this,void 0,void 0,(function*(){return e===s.FileOperation.GET?this.getAccessUrls(t,!0):t.map((e=>`${this.fileServerUrl}/?objectKey="/${e}"`))}))}moveObject(e){return o(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>r.default.post(`${this.fileServerUrl}/`,{from:e.fromURI,to:e.toURI}))))}))}copyObject(e){return o(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>r.default.post(`${this.fileServerUrl}/`,{from:e.fromURI,to:e.toURI,copy:!0}))))}))}removeObject(e){return o(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>r.default.delete(`${this.fileServerUrl}/?objectKey="/${e}"`))))}))}}t.LocalFileService=LocalFileService},5991:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalMailService=void 0;const r=n(i(7147)),s=n(i(1017)),a=i(4487);class LocalMailService extends a.AbstractMailService{constructor(e){super(),this.folderPath=e,r.default.existsSync(this.folderPath)||r.default.mkdirSync(e,{recursive:!0})}send(e){return o(this,void 0,void 0,(function*(){const t=s.default.join(this.folderPath,`${Date.now()}.html`);r.default.writeFileSync(t,`\n From: ${e.sender}\n\n To: ${e.receivers.join(", ")}\n\n Cc: ${(e.cc||[]).join(", ")}\n\n Bcc: ${(e.bcc||[]).join(", ")}\n\n\n Subject: ${e.subject}\n\n Content: ${e.contentType}\n\n ${e.content}\n `.trim())}))}}t.LocalMailService=LocalMailService},3912:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalSmsService=void 0;const r=n(i(7147)),s=n(i(1017)),a=i(7120);class LocalSmsService extends a.AbstractSmsService{constructor(e){super(),this.folderPath=e,r.default.existsSync(this.folderPath)||r.default.mkdirSync(this.folderPath,{recursive:!0})}send(e,t,i){return o(this,void 0,void 0,(function*(){const o=s.default.join(this.folderPath,`${Date.now()}`);r.default.writeFileSync(o,`${e}-${t}: ${i}\n`)}))}}t.LocalSmsService=LocalSmsService},6135:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.S3FileService=void 0;const s=i(2318),a=i(9336),d=i(7179);let l=class S3FileService extends d.AbstractFileService{constructor(e,t){super(),this.config=e,this.logger=t,this.s3Client=new a.S3({signatureVersion:"v4",region:this.config.S3_BUCKET_REGION}),this.cloudfrontSigner=new a.CloudFront.Signer(this.config.CLOUD_FRONT_PUBLIC_KEY_ID,Buffer.from(this.config.CLOUD_FRONT_PRIVATE_KEY_BASE64,"base64").toString())}getFileSize(e){return r(this,void 0,void 0,(function*(){return yield Promise.all(e.map((e=>this.getSingleFileSize(e))))}))}getAccessUrls(e,t){return r(this,void 0,void 0,(function*(){return e.map((e=>this.getSingleAccessUrl(e,t)))}))}getPresignedUrl(e,t){return r(this,void 0,void 0,(function*(){return t.map((t=>this.getSinglePresignedUrl(e,t)))}))}moveObject(e){return r(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>this.moveSingleObject(e.fromURI,e.toURI))))}))}copyObject(e){return r(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>this.copySingleObject(e.fromURI,e.toURI))))}))}removeObject(e){return r(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>this.removeSingleObject(e))))}))}getSingleFileSize(e){return r(this,void 0,void 0,(function*(){return(yield this.s3Client.headObject({Key:e,Bucket:this.config.S3_BUCKET_NAME}).promise().then((e=>e.ContentLength)))||0}))}getSinglePresignedUrl(e,t){return this.cloudfrontSigner.getSignedUrl({url:`${this.config.CLOUD_FRONT_PUBLIC_DOMAIN}/${t}`,expires:Date.now()+36e5})}copySingleObject(e,t){return r(this,void 0,void 0,(function*(){try{yield this.s3Client.copyObject({Bucket:this.config.S3_BUCKET_NAME,CopySource:`/${this.config.S3_BUCKET_NAME}/${e}`,Key:t}).promise()}catch(e){throw this.logger.error(e),e}}))}moveSingleObject(e,t){return r(this,void 0,void 0,(function*(){try{yield this.copySingleObject(e,t),yield this.removeSingleObject(e)}catch(e){throw this.logger.error(e),e}}))}getSingleAccessUrl(e,t){const i=`${this.config.CLOUD_FRONT_PUBLIC_DOMAIN}/${e}`;return t?i:this.cloudfrontSigner.getSignedUrl({url:i,expires:Date.now()+1e3*this.config.PRESIGNED_URL_EXPIRATION_S})}removeSingleObject(e){return r(this,void 0,void 0,(function*(){yield this.s3Client.deleteObject({Bucket:this.config.S3_BUCKET_NAME,Key:e}).promise()}))}};l=o([(0,s.LogContext)(),n("design:paramtypes",[Object,s.AbstractLogger])],l),t.S3FileService=l},1786:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.SesMailService=void 0;const s=i(2318),a=i(9336),d=i(4487);let l=class SesMailService extends d.AbstractMailService{constructor(e,t){super(),this.config=e,this.logger=t,this.emailClient=new a.SES({apiVersion:"2010-12-01",region:this.config.SES_REGION})}send(e){return r(this,void 0,void 0,(function*(){try{const t={Destination:{BccAddresses:e.bcc,CcAddresses:e.cc,ToAddresses:e.receivers},Message:{Body:{},Subject:{Charset:"UTF-8",Data:e.subject}},Source:e.sender};"html"===e.contentType?t.Message.Body.Html={Charset:"UTF-8",Data:e.content}:"text"===e.contentType&&(t.Message.Body.Text={Charset:"UTF-8",Data:e.content}),yield this.emailClient.sendEmail(t).promise()}catch(e){throw this.logger.error(e),s.Errors.SYSTEM_ERROR("Cannot send email")}}))}};l=o([(0,s.LogContext)(),n("design:paramtypes",[Object,s.AbstractLogger])],l),t.SesMailService=l},6862:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocket=void 0;const n=i(2318);t.AbstractServerSocket=class AbstractServerSocket{constructor(e){this.socketInfo=e}getId(){return this.socketInfo.id}getAuthInfo(){return this.socketInfo.authInfo}send(e,t){return o(this,void 0,void 0,(function*(){t?this.socketInfo.channels.find((e=>e.name===t&&e.serverToClientAllowed))&&(yield this.sendRaw({type:n.MessageType.PLAIN,data:{message:e,channel:t}})):yield this.sendRaw({type:n.MessageType.PLAIN,data:{message:e}})}))}sendRaw(e){return o(this,void 0,void 0,(function*(){yield this.physicSend(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,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocketManager=void 0;const r=i(2318),s=i(2255),a=i(1532),d=i(9990),l=i(2665),c="x-socket-action",u="read",p="write";let h=class SocketReadCondition extends s.AbstractAccessCondition{resolveConditionValue(e){return n(this,void 0,void 0,(function*(){return e.headers["x-socket-action"]===u}))}validate(e){return n(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"disable_write",description:"Disable send message to channel",valueType:r.AccessConditionValueType.BOOLEAN}}};h=o([(0,r.Register)()],h);let f=class SocketWriteCondition extends s.AbstractAccessCondition{resolveConditionValue(e){return n(this,void 0,void 0,(function*(){return e.headers["x-socket-action"]===p}))}validate(e){return n(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"disable_read",description:"Disable receive message from channel",valueType:r.AccessConditionValueType.BOOLEAN}}};f=o([(0,r.Register)()],f);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e,t,i,o,n){this.requireAuthentication=e,this.logger=t,this.redisClient=i,this.principalResolver=o,this.requestAuthorizer=n,this._connectionHandler=null}getUniqueChannelPrefix(){return"CHANNEL:"}getSocketInfoHashKey(){return"__SOCKET_INFO__"}getConnectionHandler(){return n(this,void 0,void 0,(function*(){if(null===this._connectionHandler){const e=(0,r.getServiceProvider)().getInjector();this._connectionHandler=e.resolveOptional(d.AbstractSocketConnectionHandler),yield e.initInstances()}return this._connectionHandler}))}formatBroadcastData(e,t){return{type:r.MessageType.PLAIN,data:{channel:e,message:t}}}getUniqueChannelName(e){return`${this.getUniqueChannelPrefix()}${e}`}getSocketIdsOfChannel(e){return n(this,void 0,void 0,(function*(){return(yield this.redisClient.smembers(this.getUniqueChannelName(e)))||[]}))}addSocketToChannel(e,t){return n(this,void 0,void 0,(function*(){const i=yield this.getById(e);return i&&(i.addChannels(t),yield Promise.all(t.map((t=>this.redisClient.sadd(this.getUniqueChannelName(t.name),e)))),yield i.saveSocketInfo()),i}))}removeSocketFromChannel(e,t,i=!0){return n(this,void 0,void 0,(function*(){if(!t.length)return;const o=yield this.getById(e);o&&(o.removeChannels(t),yield Promise.all(t.map((t=>this.redisClient.srem(this.getUniqueChannelName(t),e)))),i&&(yield o.saveSocketInfo()))}))}removeSocket(e,t=!0){return n(this,void 0,void 0,(function*(){const t=yield this.getById(e);t&&(this.logger.debug("Remove from all channels"),yield this.removeSocketFromChannel(e,t.getChannelsInfo().map((e=>e.name)),!1)),this.logger.debug("Remove from redis"),yield this.redisClient.hdel(this.getSocketInfoHashKey(),e)}))}handle(e){return n(this,void 0,void 0,(function*(){this.logger.debug("Handle socket data",e);const t=yield this.getConnectionHandler();switch(e.method){case r.SocketMethod.CONNECT:{this.logger.debug("Socket connection attempt",e);const t=new a.HttpRequest({method:r.SocketMethod.CONNECT,query:e.data.queries,pathName:""}),i=yield this.principalResolver.resolvePrincipal(t);if(!i&&this.requireAuthentication)throw r.Errors.ACCESS_DENIED("Authentication required");yield this.addSocket({id:e.socketId,authInfo:i,channels:[],createdAt:Date.now()},e.data);break}case r.SocketMethod.DISCONNECT:{this.logger.debug("Socket disconnect",e);const i=yield this.getById(e.socketId);if(i){const e=yield this.getMountedEndpointInfo();this.logger.debug("Notify channels");for(const t of i.getChannelsInfo()){const o=e.find((e=>e.endpointMetadata.url===t.name));o&&o.endpoint.controller.onChannelLeave(i)}this.logger.debug("Calling disconnection handler"),null==t||t.onSocketDisconnect(i),this.logger.debug("Removing socket"),yield this.removeSocket(i.getId(),!1)}break}case r.SocketMethod.MESSAGE:{this.logger.debug("Socket message",e);const i=e.data;let o=yield this.getById(e.socketId);if(o)switch(i.type){case r.MessageType.READY:yield o.sendRaw({type:r.MessageType.READY,data:""}),yield null==t?void 0:t.onSocketConnect(o);break;case r.MessageType.PING_PONG:yield o.sendRaw({type:r.MessageType.PING_PONG,data:i.data});break;case r.MessageType.CHANNEL_JOIN:{const e=i.data,t=[],n=[];for(const i of e){let e=!1,o=!1;const s=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===i));if(s){try{const e=new a.HttpRequest({method:r.SocketMethod.MESSAGE,pathName:i,headers:{[c]:u}},s.endpointMetadata);yield this.requestAuthorizer.authorize(e,s),o=!0}catch(e){this.logger.debug("Error in read authorize",e)}try{const t=new a.HttpRequest({method:r.SocketMethod.MESSAGE,pathName:i,headers:{[c]:p}},s.endpointMetadata);yield this.requestAuthorizer.authorize(t,s),e=!0}catch(e){this.logger.debug("Error in write authorize",e)}(e||o)&&(this.logger.debug("Adding channel info",i,e,o),t.push({name:i,clientToServerAllowed:e,serverToClientAllowed:o}),n.push(s))}}o=yield this.addSocketToChannel(o.getId(),t),o?yield Promise.all([o.sendRaw({type:r.MessageType.CHANNEL_JOIN,data:t.map((e=>e.name))}),...n.map((e=>e.endpoint.controller.onChannelJoin(o)))]):this.logger.debug("Socket not found after addSocketToChannel")}break;case r.MessageType.CHANNEL_LEAVE:{const e=i.data,t=yield this.getMountedEndpointInfo();Promise.all(e.map((e=>()=>{const i=t.find((t=>t.endpointMetadata.url===e));if(i)return i.endpoint.controller.onChannelLeave(o)}))),yield this.removeSocketFromChannel(o.getId(),e)}break;case r.MessageType.PLAIN:{const e=i.data.channel,n=i.data.message;if(e){if(o.getChannelsInfo().find((t=>t.name===e&&t.clientToServerAllowed))){const t=(yield this.getMountedEndpointInfo()).find((t=>t.endpointMetadata.url===e));if(t){!1!==(yield t.endpoint.controller.onMessage(o,n))&&(this.logger.debug("broadcasting to channel",e,n),this.broadcastToChannel(e,n))}}}else yield null==t?void 0:t.onMessage(o,n)}break;default:this.logger.debug("Invalid message format",i)}else this.logger.debug("Socket not found",e.socketId);break}default:return}}))}getMountedEndpointInfo(){return n(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const e=(0,r.getServiceProvider)().getInjector(),t=e.resolveMultiple(l.AbstractSocketController);yield e.initInstances(),this.mountedEndpointInfo=t.map((e=>{const t=(0,r.getObjectMetadata)(e.constructor);return{endpoint:{httpMethod:r.SocketMethod.MESSAGE,mount:e.getChannelName(),controller:e,handlerFunctionName:e.onMessage.name},endpointMetadata:{httpMethod:r.SocketMethod.MESSAGE,description:"Send / Receive message to / from channel",permissionGroup:t.permissionGroup,dataType:r.DataType.OBJECT,url:e.getChannelName(),name:e.getChannelName(),accessConditions:[h,f]}}}))}return this.mountedEndpointInfo}))}}},9990:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketConnectionHandler=void 0;t.AbstractSocketConnectionHandler=class AbstractSocketConnectionHandler{}},2665:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketController=void 0;const n=i(8985);class AbstractSocketController extends n.AbstractController{onChannelJoin(e){return o(this,void 0,void 0,(function*(){}))}onChannelLeave(e){return o(this,void 0,void 0,(function*(){}))}onMessage(e,t){return o(this,void 0,void 0,(function*(){}))}}t.AbstractSocketController=AbstractSocketController},7152:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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=i(2318),d=s(i(9336)),l=s(i(1495)),c=i(767),u=i(5530),p=i(6862),h=i(5709),f=i(4638);class ApiGatewaySocket extends p.AbstractServerSocket{constructor(e,t,i,o,n){super(t),this.socketManager=e,this.socketInfo=t,this.apiGateway=i,this.socketNamespace=o,this.redisClient=n}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.redisClient.hset(this.socketNamespace,this.socketInfo.id,JSON.stringify(this.socketInfo))}))}physicSend(e){return r(this,void 0,void 0,(function*(){yield this.socketManager.physicSend(this.getId(),e)}))}disconnect(e){return r(this,void 0,void 0,(function*(){e&&(yield this.physicSend(e)),yield this.socketManager.removeSocket(this.getId())}))}serialize(){return JSON.stringify(this.socketInfo)}}let v=class AwsSocketManager extends u.AbstractServerSocketManager{constructor(e,t,i,o,n,r,s,a){super(e,a,o,r,s),this.authenticationRequired=e,this.region=t,this.socketDomainUrl=i,this.redis=o,this.httpRequestHandler=n,this.principalResolver=r,this.requestAuthorizer=s,this.logger=a,this.apiGatewayManagement=new d.default.ApiGatewayManagementApi({region:t,apiVersion:"2018-11-29",endpoint:i})}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)}))}physicSend(e,t){return r(this,void 0,void 0,(function*(){try{this.logger.debug(`Socket ${e} sending`,t),yield this.apiGatewayManagement.postToConnection({ConnectionId:e,Data:JSON.stringify(t)}).promise()}catch(t){throw this.logger.debug(`Socket ${e} post error`,t),410===t.statusCode&&(this.logger.debug(`Disconnect & remove stale socket ${e}`),yield this.removeSocket(e,!1),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 i=yield this.getSocketIdsOfChannel(e);if(i.length){const o=this.formatBroadcastData(e,t);i.map((e=>this.physicSend(e,o).catch((t=>this.logger.error(`Cannot send to socket ${e}`,t)))))}}))}addSocket(e,t){return r(this,void 0,void 0,(function*(){const t=new ApiGatewaySocket(this,e,this.apiGatewayManagement,this.getSocketInfoHashKey(),this.redisClient);return yield t.saveSocketInfo(),t}))}removeSocket(e,t=!0){const i=Object.create(null,{removeSocket:{get:()=>super.removeSocket}});return r(this,void 0,void 0,(function*(){this.logger.debug(`Aws socket manager remove socket: ${e}, ${t}`),yield i.removeSocket.call(this,e,t),this.logger.debug("Super remove ok"),t&&this.apiGatewayManagement.deleteConnection({ConnectionId:e}).promise().catch((e=>this.logger.error("Cannot physic remove aws socket",e)))}))}getSocketBySerialized(e){return new ApiGatewaySocket(this,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)}))}};v=o([(0,a.Initable)(),(0,a.LogContext)(),n("design:paramtypes",[Boolean,String,String,l.default,c.AbstractHttpRequestHandler,f.AbstractPrincipalResolver,h.AbstractRequestAuthorizer,a.AbstractLogger])],v),t.AwsSocketManager=v},8577:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},2841:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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=i(2318),d=s(i(5352)),l=s(i(9215)),c=s(i(9103)),u=s(i(1495)),p=i(5530),h=i(6862),f=i(5709),v=i(4638);var y;!function(e){e.SEND="SEND",e.CLOSE="CLOSE",e.SAVE="SAVE"}(y||(y={}));class RedisSocket extends h.AbstractServerSocket{constructor(e,t,i){super(i),this.socketChannelName=e,this.redisClient=t,this.socketInfo=i}physicSend(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:y.SEND,data:e}))}))}disconnect(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:y.CLOSE,data:e}))}))}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:y.SAVE,data:this.socketInfo}))}))}}class ExpressSocket extends h.AbstractServerSocket{constructor(e,t,i,o){super(i),this.socketManager=e,this.socket=t,this.socketInfo=i,this.infoSaver=o}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.infoSaver(this.socketInfo)}))}physicSend(e){return r(this,void 0,void 0,(function*(){this.socket.send(JSON.stringify(e))}))}disconnect(e){return r(this,void 0,void 0,(function*(){this.socket.close(1e3,e&&JSON.stringify(e)),yield this.socketManager.removeSocket(this.getId())}))}}let g=class LocalSocketManager extends p.AbstractServerSocketManager{constructor(e,t,i,o,n,r,s){super(e,n,o,r,s),this.authenticationRequired=e,this.subClient=t,this.channelSubClient=i,this.sendClient=o,this.logger=n,this.principalResolver=r,this.requestAuthorizer=s,this.allSockets=[],this.subscribedChannels=[]}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.logger.info("LocalSocketManager exit")}channelMessageListenner(e,t){this.logger.debug("Receiving message from channel",t,e);const i=JSON.parse(e);i.type===a.MessageType.PLAIN&&this.allSockets.forEach((e=>{e.send(i.data.message,i.data.channel)}))}socketMessageListener(e,t){this.logger.debug("Receiving message from remote socket channel",t,e);const i=t.substring(this.getSocketChannelKeyPrefix().length),o=this.allSockets.find((e=>e.getId()===i));if(o){const t=JSON.parse(e);switch(t.type){case y.SEND:o.physicSend(t.data);break;case y.SAVE:o.socketInfo.channels=t.data,o.saveSocketInfo();break;case y.CLOSE:o.disconnect(t.data);break;default:this.logger.debug("Invalid remote command",t)}}}getUniqueDataChannelName(e){return`CHANNEL_DATA:${e}`}getSocketChannelKeyPrefix(){return"SOCKET_CHANNEL:"}getSocketChannelKey(e){return`${this.getSocketChannelKeyPrefix()}${e}`}broadcastToChannel(e,t){return r(this,void 0,void 0,(function*(){const i=this.formatBroadcastData(e,t);yield this.redisClient.publish(this.getUniqueDataChannelName(e),JSON.stringify(i))}))}addSocketToChannel(e,t){const i=Object.create(null,{addSocketToChannel:{get:()=>super.addSocketToChannel}});return r(this,void 0,void 0,(function*(){const o=yield i.addSocketToChannel.call(this,e,t),n=t.map((e=>e.name)).filter((e=>!this.subscribedChannels.includes(e)));return n.length&&(yield Promise.all(n.map((e=>this.channelSubClient.subscribe(this.getUniqueDataChannelName(e))))),this.subscribedChannels.push(...n)),o}))}removeSocketFromChannel(e,t,i=!0){const o=Object.create(null,{removeSocketFromChannel:{get:()=>super.removeSocketFromChannel}});return r(this,void 0,void 0,(function*(){yield o.removeSocketFromChannel.call(this,e,t,i),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 i=new ExpressSocket(this,t,e,(e=>r(this,void 0,void 0,(function*(){yield this.redisClient.hset(this.getSocketInfoHashKey(),e.id,JSON.stringify(e))})))),o=this.getSocketChannelKey(e.id);return yield this.subClient.subscribe(o),this.allSockets.push(i),i}))}removeSocket(e,t=!0){const i=Object.create(null,{removeSocket:{get:()=>super.removeSocket}});return r(this,void 0,void 0,(function*(){yield i.removeSocket.call(this,e,t);const o=this.getSocketChannelKey(e);yield this.subClient.unsubscribe(o),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 i=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)}))));i&&(t=new RedisSocket(this.getSocketChannelKey(e),this.sendClient,i))}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 i=t.headers["sec-websocket-key"];let o=!1,n=[];const r=(0,l.default)({url:t.url}),s=c.default.parse(decodeURIComponent(r.search||""));this.handle({method:a.SocketMethod.CONNECT,socketId:i,data:{queries:s,socket:e}}).then((()=>{o=!0;for(const e of n)this.handle(e).catch((e=>{this.logger.error(e)}))})).catch((t=>{n=[],e.close(1e3,`${t.name}:${t.message}`)})),e.onmessage=e=>{const t={method:a.SocketMethod.MESSAGE,socketId:i,data:e.data&&JSON.parse(e.data)};o?this.handle(t).catch((e=>{this.logger.error(e)})):n.push(t)},e.onclose=()=>{this.handle({method:a.SocketMethod.DISCONNECT,socketId:i}).catch((e=>{this.logger.error(e)}))}}))}};g=o([(0,a.Initable)(),(0,a.LogContext)(),n("design:paramtypes",[Boolean,u.default,u.default,u.default,a.AbstractLogger,v.AbstractPrincipalResolver,f.AbstractRequestAuthorizer])],g),t.LocalSocketManager=g},5537:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ClaireServer=void 0;const s=i(2318),a=i(137),d=i(767),l=i(5530),c=i(9202);let u=class ClaireServer extends s.ClaireApp{constructor(e,t,i){super(),this.logger=e,this.httpRequestHandler=t,this.socketManager=i,this.booted=!1}init(){return r(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,c.getEndpointId)(t.endpoint)}`);(0,s.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(a.ExitCode.SIGTERM_INTERUPTION)))),process.on("SIGINT",(()=>(this.logger.warn("SIGINT interrupt signal"),this.stop(a.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)}};u=o([(0,s.LogContext)(),n("design:paramtypes",[s.AbstractLogger,d.AbstractHttpRequestHandler,l.AbstractServerSocketManager])],u),t.ClaireServer=u},226:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExpressWrapper=void 0;const r=i(2318),s=n(i(6860)),a=n(i(3685)),d=n(i(9710)),l=n(i(6674)),c=n(i(3582)),u=i(5530),p=i(767);t.ExpressWrapper=class ExpressWrapper{constructor(e,t){this.server=e,this.config=t,this.injector=(0,r.getServiceProvider)().getInjector(),this.socketManager=this.injector.resolveOptional(u.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(p.AbstractHttpRequestHandler)}close(){var e;null===(e=this.httpServer)||void 0===e||e.close(),this.server.exit()}listen(e){var t,i,n,u;return o(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances();const p=(0,s.default)(),h=a.default.createServer(p);null===(t=this.socketManager)||void 0===t||t.configure(h),(null===(i=this.httpRequestHandler)||void 0===i?void 0:i.corsConfig)&&p.use((0,c.default)({allowedHeaders:this.httpRequestHandler.corsConfig.headers,credentials:this.httpRequestHandler.corsConfig.credentials,origin:this.httpRequestHandler.corsConfig.origins,methods:this.httpRequestHandler.corsConfig.methods}));const f=1024*((null===(u=null===(n=this.config)||void 0===n?void 0:n.requestSetting)||void 0===u?void 0:u.maxBodySizeKB)||10240);return p.use((0,d.default)()),p.use(s.default.json({limit:f})),p.use(s.default.urlencoded({extended:!1,limit:f})),p.use((0,l.default)()),p.use(((e,t,i)=>{e.files&&(e.body||(e.body={}),Object.keys(e.files).forEach((t=>{e.body[t]=e.files[t]}))),i()})),p.use(s.default.raw({limit:f,type:e=>!["application/json","application/x-www-form-urlencoded"].find((t=>{var i;return null===(i=e.headers["content-type"])||void 0===i?void 0:i.includes(t)}))})),p.all("*",((e,t)=>{(()=>o(this,void 0,void 0,(function*(){if(!!e.headers["x-amzn-apigateway-api-id"]){if(!this.socketManager)throw r.Errors.SYSTEM_ERROR("Socket manager not found");const i={socketId:e.body.connectionId,data:e.body.data,method:e.body.type.toLowerCase()};if(i.method===r.SocketMethod.CONNECT){const t=e.body.data.querystring,o=t.substring(1,t.length-1).split(",").map((e=>e.trim().split("="))).reduce(((e,t)=>Object.assign(e,{[t[0]]:t[1]})),{});i.data={queries:o}}yield this.socketManager.handle(i),t.status(200).send()}else{if(!this.httpRequestHandler)throw r.Errors.SYSTEM_ERROR("Http request handler not found");const i={clientIP:e.ip||e.headers["x-forwarded-for"],fullPath:e.url,method:e.method.toLowerCase(),headers:e.headers,body:e.body,cookies:e.cookies},o=yield this.httpRequestHandler.handle(i);o.headers&&Object.keys(o.headers).forEach((e=>{t.set(e,o.headers[e])})),o.cookies&&Object.keys(o.cookies).forEach((e=>{t.cookie(e,o.cookies[e].value,o.cookies[e].options||{})})),t.status(o.code||200).send(o.value)}})))().catch((e=>{t.status(e.code||500).json({name:e.name,message:e.message,code:e.code||500})}))})),new Promise(((t,i)=>{this.httpServer=h.listen(e,t).on("error",i)}))}))}}},8836:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=void 0;const n=i(2318),r=i(767),s=i(3376),a=i(2363),d=i(5530),toApiGatewayFormat=e=>({statusCode:e.code||200,body:e.value&&JSON.stringify(e.value),headers:e.headers,cookies:Object.keys(e.cookies||{}).map((t=>{var i,o,n,r,s,a,d,l,c,u,p;const h=e.cookies[t];let f=`${t}=${h.value}`;return(null===(i=h.options)||void 0===i?void 0:i.maxAge)&&(f+=`; MaxAge=${h.options.maxAge}`),(null===(o=h.options)||void 0===o?void 0:o.expires)&&(f+=`; Expires=${h.options.expires.toUTCString()}`),(null===(n=h.options)||void 0===n?void 0:n.httpOnly)&&(f+="; HttpOnly"),(null===(r=h.options)||void 0===r?void 0:r.path)&&(f+=`; Path=${null===(s=h.options)||void 0===s?void 0:s.path}`),(null===(a=h.options)||void 0===a?void 0:a.domain)&&(f+=`; Domain=${null===(d=h.options)||void 0===d?void 0:d.domain}`),(null===(l=h.options)||void 0===l?void 0:l.secure)&&(f+="; Secure"),(null===(c=h.options)||void 0===c?void 0:c.sameSite)&&("boolean"==typeof(null===(u=h.options)||void 0===u?void 0:u.sameSite)?f+="; SameSite":f+=`; SameSite=${null===(p=h.options)||void 0===p?void 0:p.sameSite}`),f}))});t.LambdaWrapper=class LambdaWrapper{constructor(e,t,i){this.serverFactory=e,this.requestMapper=t,this.config=i,this.injector=(0,n.getServiceProvider)().getInjector(),this.handler=this.handler.bind(this),this.socketManager=this.injector.resolveOptional(d.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(r.AbstractHttpRequestHandler),this.jobScheduler=this.injector.resolveOptional(s.AwsJobScheduler)}bootServer(){var e;return o(this,void 0,void 0,(function*(){this._server||(this._server=yield this.serverFactory(),yield this.injector.initInstances(),null===(e=this.socketManager)||void 0===e||e.configure(),yield this._server.init())}))}handler(e){var t,i,r,s;return o(this,void 0,void 0,(function*(){yield this.bootServer();const o=this.requestMapper(e);if(!o)throw n.Errors.SYSTEM_ERROR("Cannot resolve event");const d=((e,t)=>{const i={};return(null==t?void 0:t.credentials)&&(i["Access-Control-Allow-Credentials"]="true"),(null==t?void 0:t.headers)&&(i["Access-Control-Allow-Headers"]="string"==typeof t.headers?t.headers:t.headers.join(", ")),(null==t?void 0:t.methods)&&(i["Access-Control-Allow-Methods"]="string"==typeof t.methods?t.methods:t.methods.join(", ")),(null==t?void 0:t.origins)&&(i["Access-Control-Allow-Origin"]="string"==typeof t.origins?t.origins:t.origins.find((t=>e.match(t)))?e:""),i})((null===(t=o.headers)||void 0===t?void 0:t.origin)||"",null===(i=this.httpRequestHandler)||void 0===i?void 0:i.corsConfig);if(o.method===n.HttpMethod.OPTIONS)return toApiGatewayFormat({code:200,headers:d,cookies:{}});if(o.method===a.INTERVAL_REQUEST_METHOD)return yield null===(r=this.jobScheduler)||void 0===r?void 0:r.handleInterval(o.body),toApiGatewayFormat({code:200,headers:d,cookies:{}});if(o.method===a.CRON_REQUEST_METHOD)return yield null===(s=this.jobScheduler)||void 0===s?void 0:s.handleCron(o.body),toApiGatewayFormat({code:200,headers:d,cookies:{}});try{if(Object.values(n.HttpMethod).includes(o.method)){if(!this.httpRequestHandler)throw n.Errors.SYSTEM_ERROR("Http request handler not found");const e={clientIP:o.clientIP,fullPath:o.rawPath,method:o.method,headers:o.headers,cookies:o.cookies,body:o.body},t=yield this.httpRequestHandler.handle(e);return toApiGatewayFormat(Object.assign(Object.assign({},t),{headers:Object.assign(Object.assign({},d),t.headers)}))}if(!Object.values(n.SocketMethod).includes(o.method))throw n.Errors.HTTP_REQUEST_ERROR("Not allow request method: "+o.method);{if(!this.socketManager)throw n.Errors.SYSTEM_ERROR("Socket manager not found");const e={socketId:o.rawPath,method:o.method,data:o.body};yield this.socketManager.handle(e)}return toApiGatewayFormat({code:200,headers:d,cookies:{}})}catch(e){return toApiGatewayFormat({code:e.code||500,value:{name:e.name,message:e.message,code:e.code||500},headers:d,cookies:{}})}}))}}},9627:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},889:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lambdaRequestMapper=void 0;const o=i(2318),n=i(2363),parseCookie=e=>{let t={};for(const i of e){const e=i.split("=");e[0]&&e[1]&&(t[e[0]]=e[1])}return t};t.lambdaRequestMapper=e=>{if(e.requestContext.eventType){const t=e.requestContext.eventType.toLowerCase(),i=e.body&&JSON.parse(e.body);return{method:t,rawPath:e.requestContext.connectionId,body:t===o.SocketMethod.CONNECT?{queries:e.queryStringParameters}:i}}return e.requestContext.intervalScheduler?{method:n.INTERVAL_REQUEST_METHOD,rawPath:"",body:e.requestContext.intervalScheduler.time}:e.requestContext.cronScheduler?{method:n.CRON_REQUEST_METHOD,rawPath:"",body:e.requestContext.cronScheduler.data}:{clientIP:e.requestContext.http.sourceIp,method:e.requestContext.http.method.toLowerCase(),rawPath:`${e.rawPath}?${e.rawQueryString}`,body:e.body&&JSON.parse(e.body),headers:e.headers,cookies:parseCookie(e.cookies||[])}}},5481:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s};Object.defineProperty(t,"__esModule",{value:!0}),t.LocaleEntry=void 0;const n=i(2318);let r=class LocaleEntry extends n.AbstractModel{};r=o([(0,n.Model)()],r),t.LocaleEntry=r},2552:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};Object.defineProperty(t,"__esModule",{value:!0}),t.LocaleTranslation=void 0;const r=i(2318),s=i(5481);let a=class LocaleTranslation extends r.AbstractModel{};o([(0,r.Column)(Object.assign({description:"Id of the locale",isRequired:!0},(0,r.FK)({model:s.LocaleEntry,cascade:"delete"}))),n("design:type",String)],a.prototype,"entryId",void 0),o([(0,r.Column)({description:"Code of locale",isRequired:!0,textLength:3}),n("design:type",String)],a.prototype,"localeCode",void 0),o([(0,r.Column)({description:"Translation of locale",isRequired:!0}),n("design:type",String)],a.prototype,"translation",void 0),a=o([(0,r.Model)(),(0,r.Index)([["entryId",1],["localeCode",1]],{unique:!0})],a),t.LocaleTranslation=a},10:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LocaleOf=void 0;const o=i(2318),n=i(5481);t.LocaleOf=e=>(t,i)=>{const r=(0,o.initFieldMetadata)(t,i);r.multiLocaleColumn=e,r.fk=(0,o.FK)({model:n.LocaleEntry,cascade:"nullify"}).fk,r.dataType=o.DataType.NUMBER;(0,o.initFieldMetadata)(t,e).isMultiLocale=!0}},2318:e=>{e.exports=require("@clairejs/core")},7756:e=>{e.exports=require("@clairejs/orm")},9336:e=>{e.exports=require("aws-sdk")},2167:e=>{e.exports=require("axios")},9710:e=>{e.exports=require("cookie-parser")},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")},7344:e=>{e.exports=require("node-schedule")},9215:e=>{e.exports=require("parseurl")},99:e=>{e.exports=require("path-to-regexp")},9103:e=>{e.exports=require("query-string")},7325:e=>{e.exports=require("randomstring")},9896:e=>{e.exports=require("redlock")},5352:e=>{e.exports=require("ws")},7147:e=>{e.exports=require("fs")},3685:e=>{e.exports=require("http")},1017:e=>{e.exports=require("path")},9512:e=>{e.exports=require("timers")}},t={};var i=function __webpack_require__(i){var o=t[i];if(void 0!==o)return o.exports;var n=t[i]={exports:{}};return e[i].call(n.exports,n,n.exports,__webpack_require__),n.exports}(341);return i})()));
|
|
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 i=t();for(var o in i)("object"==typeof exports?exports:e)[o]=i[o]}}(global,(()=>(()=>{"use strict";var e={8985:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractController=void 0;const o=i(5007);class AbstractController extends o.Transactionable{}t.AbstractController=AbstractController},2872:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},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={}))},5007:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Transactionable=void 0;const n=i(2318),r=i(7756);t.Transactionable=class Transactionable{constructor(e){this.transactionFactory=e}createTransaction(){return o(this,void 0,void 0,(function*(){if(!this.transactionFactory)throw n.Errors.SYSTEM_ERROR("Transaction factory not injected to this class");return this.transactionFactory.createTransaction()}))}getCurrentTransaction(){return o(this,void 0,void 0,(function*(){return(0,r.getTransactionFromContext)(this)}))}}},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=void 0,t.ExitCode={SIGTERM_INTERUPTION:-1,SIGINT_INTERUPTION:-2,UNCAUGHT_EXCEPTION:-3,UNHANDLED_REJECTION:-4}},7678:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Controller=void 0;const o=i(2318);t.Controller=e=>t=>{(0,o.getServiceProvider)().register(t,"singleton");(0,o.initObjectMetadata)(t.prototype).permissionGroup=null==e?void 0:e.permissionGroup}},4435:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},4972:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},1870:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},7540:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},7380:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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(i,o){t(i,o,e)}},s=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FileManageController=void 0;const a=i(2318),d=i(8903),l=i(6004),c=i(2417),u=i(7179),p=i(7724);let h=class FileManageController extends l.AbstractHttpController{constructor(e){super(null),this.fileService=e}moveFile(e){return s(this,void 0,void 0,(function*(){return yield this.fileService.moveObject(e.operations),d.ResponseBuilder.success()}))}copyFile(e){return s(this,void 0,void 0,(function*(){return yield this.fileService.copyObject(e.operations),d.ResponseBuilder.success()}))}removeFile(e){return s(this,void 0,void 0,(function*(){return yield this.fileService.removeObject(e.uris),d.ResponseBuilder.success()}))}getFileAccessUrl(e){return s(this,void 0,void 0,(function*(){const t=yield this.fileService.getAccessUrls(e.uris,e.public);return d.ResponseBuilder.json({urls:t}).get()}))}getFileInfo(e){return s(this,void 0,void 0,(function*(){const t={fileInfos:(yield this.fileService.getFileSize(e.uris)).map((e=>({fileSizeBytes:e})))};return d.ResponseBuilder.json(t).get()}))}};o([(0,c.Post)("/file/move"),r(0,(0,c.Body)()),n("design:type",Function),n("design:paramtypes",[p.MoveFileRequest]),n("design:returntype",Promise)],h.prototype,"moveFile",null),o([(0,c.Post)("/file/copy"),r(0,(0,c.Body)()),n("design:type",Function),n("design:paramtypes",[p.MoveFileRequest]),n("design:returntype",Promise)],h.prototype,"copyFile",null),o([(0,c.Post)("/file/remove"),r(0,(0,c.Body)()),n("design:type",Function),n("design:paramtypes",[p.RemoveFileRequest]),n("design:returntype",Promise)],h.prototype,"removeFile",null),o([(0,c.Get)("/file"),(0,c.ApiResponse)(p.GetFileAccessUrlResponse),r(0,(0,c.Queries)()),n("design:type",Function),n("design:paramtypes",[p.GetFileAccessUrlRequest]),n("design:returntype",Promise)],h.prototype,"getFileAccessUrl",null),o([(0,c.Get)("/file/info"),(0,c.ApiResponse)(p.GetFileInfoResponse),r(0,(0,c.Queries)()),n("design:type",Function),n("design:paramtypes",[p.GetFileInfoRequest]),n("design:returntype",Promise)],h.prototype,"getFileInfo",null),h=o([(0,a.Injectable)(),n("design:paramtypes",[u.AbstractFileService])],h),t.FileManageController=h},8037:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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(i,o){t(i,o,e)}},s=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.FileUploadController=void 0;const d=i(2318),l=a(i(7325)),c=i(8903),u=i(6004),p=i(2417),h=i(7179),f=i(7724);let v=class FileUploadController extends u.AbstractHttpController{constructor(e,t){super(null),this.fileService=e,this.allowedUploadExtensions=t}getUploadUrl(e){var t;return s(this,void 0,void 0,(function*(){const i=null===(t=e.extension)||void 0===t?void 0:t.toLowerCase();if(i&&!this.allowedUploadExtensions.includes(i))throw d.Errors.VALIDATION_ERROR("Not allowed file extension");const o=yield this.fileService.getUploadUrlForTempUri(`tmp/${l.default.generate({length:64})}${i?`.${i}`:""}`);return c.ResponseBuilder.json(o).get()}))}getMultipleUploadUrls(e){return s(this,void 0,void 0,(function*(){if(e.extensions.some((e=>!this.allowedUploadExtensions.includes(e))))throw d.Errors.VALIDATION_ERROR("Not allowed file extension");const t=yield Promise.all(e.extensions.map((e=>this.fileService.getUploadUrlForTempUri(`tmp/${l.default.generate({length:64})}${e?`.${e}`:""}`))));return c.ResponseBuilder.json({files:t}).get()}))}};o([(0,p.Get)("/upload-url"),(0,p.ApiResponse)(f.GetUploadUrlResponseBody),r(0,(0,p.Queries)()),n("design:type",Function),n("design:paramtypes",[f.GetUploadUrlQueries]),n("design:returntype",Promise)],v.prototype,"getUploadUrl",null),o([(0,p.Get)("/upload-urls"),(0,p.ApiResponse)(f.GetMultipleUploadResponseBody),r(0,(0,p.Queries)()),n("design:type",Function),n("design:paramtypes",[f.GetMultipleUploadUrlsQueries]),n("design:returntype",Promise)],v.prototype,"getMultipleUploadUrls",null),v=o([(0,d.Injectable)(),n("design:paramtypes",[h.AbstractFileService,Array])],v),t.FileUploadController=v},2345:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UserVerificationMethod=t.CacheOperation=void 0,function(e){e.GET="get",e.KEYS="keys",e.HGET="hget",e.HKEYS="hkeys",e.FLUSH="flush"}(t.CacheOperation||(t.CacheOperation={})),function(e){e.SMS_OTP="SMS",e.VOICE_OTP="VOICE",e.MANUAL_OTP="MANUAL"}(t.UserVerificationMethod||(t.UserVerificationMethod={}))},7724:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};Object.defineProperty(t,"__esModule",{value:!0}),t.GetFileInfoResponse=t.FileInfo=t.GetFileInfoRequest=t.GetFileAccessUrlResponse=t.GetFileAccessUrlRequest=t.RemoveFileRequest=t.MoveFileRequest=t.MoveOperation=t.GetMultipleUploadResponseBody=t.GetMultipleUploadUrlsQueries=t.GetUploadUrlResponseBody=t.GetUploadUrlQueries=void 0;const r=i(2318);let s=class GetUploadUrlQueries{};o([(0,r.Field)({description:"Extension of the file to be uploaded (without dot)"}),n("design:type",String)],s.prototype,"extension",void 0),s=o([(0,r.Data)()],s),t.GetUploadUrlQueries=s;let a=class GetUploadUrlResponseBody{};o([(0,r.Field)({description:"Object key of file that store in the server",isRequired:!0}),n("design:type",String)],a.prototype,"objectKey",void 0),o([(0,r.Field)({description:"Presigned URl to put the file to server"}),n("design:type",String)],a.prototype,"putPresignedUrl",void 0),o([(0,r.Field)({description:"Presigned URL to remove the temporary file from server",isRequired:!0}),n("design:type",String)],a.prototype,"deletePresignedUrl",void 0),a=o([(0,r.Data)()],a),t.GetUploadUrlResponseBody=a;let d=class GetMultipleUploadUrlsQueries{};o([(0,r.Field)({description:"Extensions of those files",isRequired:!0,vectorProps:{allowDuplicated:!0}}),n("design:type",Array)],d.prototype,"extensions",void 0),d=o([(0,r.Data)({relaxed:!0})],d),t.GetMultipleUploadUrlsQueries=d;class GetMultipleUploadResponseBody{}o([(0,r.Field)(Object.assign({description:"Upload urls for files",vectorProps:{elementDataType:r.DataType.OBJECT}},(0,r.ElementDto)(a))),n("design:type",Array)],GetMultipleUploadResponseBody.prototype,"files",void 0),t.GetMultipleUploadResponseBody=GetMultipleUploadResponseBody;let l=class MoveOperation{};o([(0,r.Field)({description:"Source of move operation",isRequired:!0}),n("design:type",String)],l.prototype,"fromURI",void 0),o([(0,r.Field)({description:"Destination of move operation",isRequired:!0}),n("design:type",String)],l.prototype,"toURI",void 0),l=o([(0,r.Data)()],l),t.MoveOperation=l;let c=class MoveFileRequest{};o([(0,r.Field)(Object.assign({description:"All move operations",isRequired:!0,vectorProps:{elementDataType:r.DataType.OBJECT}},(0,r.ElementDto)(l))),n("design:type",Array)],c.prototype,"operations",void 0),c=o([(0,r.Data)()],c),t.MoveFileRequest=c;let u=class RemoveFileRequest{};o([(0,r.Field)({description:"File URIs to remove",isRequired:!0,vectorProps:{elementDataType:r.DataType.STRING}}),n("design:type",Array)],u.prototype,"uris",void 0),u=o([(0,r.Data)()],u),t.RemoveFileRequest=u;let p=class GetFileAccessUrlRequest{};o([(0,r.Field)({description:"All URIs to get access link",isRequired:!0,vectorProps:{elementDataType:r.DataType.STRING}}),n("design:type",Array)],p.prototype,"uris",void 0),o([(0,r.Field)({description:"Whether to get public or private link",isRequired:!0}),n("design:type",Boolean)],p.prototype,"public",void 0),p=o([(0,r.Data)({relaxed:!0})],p),t.GetFileAccessUrlRequest=p;let h=class GetFileAccessUrlResponse{};o([(0,r.Field)({description:"File access URLs",isRequired:!0,vectorProps:{elementDataType:r.DataType.STRING}}),n("design:type",Array)],h.prototype,"urls",void 0),h=o([(0,r.Data)()],h),t.GetFileAccessUrlResponse=h;let f=class GetFileInfoRequest{};o([(0,r.Field)({description:"File URIs to get info",isRequired:!0,vectorProps:{elementDataType:r.DataType.STRING}}),n("design:type",Array)],f.prototype,"uris",void 0),f=o([(0,r.Data)({relaxed:!0})],f),t.GetFileInfoRequest=f;let v=class FileInfo{};o([(0,r.Field)({description:"Size of file in bytes",isRequired:!0}),n("design:type",Number)],v.prototype,"fileSizeBytes",void 0),v=o([(0,r.Data)()],v),t.FileInfo=v;let y=class GetFileInfoResponse{};o([(0,r.Field)(Object.assign({description:"File infos",isRequired:!0,vectorProps:{elementDataType:r.DataType.OBJECT}},(0,r.ElementDto)(v))),n("design:type",Array)],y.prototype,"fileInfos",void 0),y=o([(0,r.Data)()],y),t.GetFileInfoResponse=y},5709:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRequestAuthorizer=void 0;t.AbstractRequestAuthorizer=class AbstractRequestAuthorizer{}},1532:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HttpRequest=void 0;const o=i(2318);t.HttpRequest=class HttpRequest{constructor(e,t){this.endpointMetadata=t,this.valueHolder={},this.params={},this.query={},this.body={},this.clientIP=e.clientIP,this.method=e.method,this.pathName=e.pathName,this.headers=e.headers||{},this.cookies=e.cookies||{},this.hash=e.hash||"",this.params.data=e.params||{},this.query.data=e.query||{},this.body.data=e.body||{}}jsonParsing(e,t){const i=Object.assign({},e);for(const n of t.fields)try{(void 0!==e[n.name]||n.isRequired)&&(i[n.name]=JSON.parse(e[n.name]))}catch(e){throw o.Errors.VALIDATION_ERROR(`JSON parsing failed for field ${n.name}`)}return i}getAuthInfo(){return this.authInfo}setAuthInfo(e){this.authInfo=e}getParams(){var e;return(null===(e=this.endpointMetadata)||void 0===e?void 0:e.paramsValidationDto)&&!this.params.validated&&(this.params.data=(0,o.validateData)(this.params.data,this.endpointMetadata.paramsValidationDto),this.params.validated=!0),this.params.data}getQuery(){var e;return(null===(e=this.endpointMetadata)||void 0===e?void 0:e.queriesValidationDto)&&!this.query.validated&&(this.query.data=(0,o.validateData)(this.jsonParsing(this.query.data,this.endpointMetadata.queriesValidationDto),this.endpointMetadata.queriesValidationDto),this.query.validated=!0),this.query.data}getBody(){var e;return this.endpointMetadata&&(this.endpointMetadata.httpMethod===o.HttpMethod.POST||this.endpointMetadata.httpMethod===o.HttpMethod.PUT)&&(null===(e=this.endpointMetadata)||void 0===e?void 0:e.bodyValidationDto)&&(this.body.data=(0,o.validateData)(this.body.data,this.endpointMetadata.bodyValidationDto,!1),this.body.validated=!0),this.body.data}}},8903:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ResponseBuilder=t.HttpResponse=void 0;class HttpResponse{constructor(){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,i){return this.response.cookies[e]={value:t,options:i},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=403,t.response.value=e,t.response}}t.ResponseBuilder=ResponseBuilder},6004:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpController=void 0;const o=i(2318),n=i(8985);class AbstractHttpController extends n.AbstractController{constructor(e){super(e),this.databaseAdapter=e}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}))):[]}}t.AbstractHttpController=AbstractHttpController},225:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpMiddleware=void 0;t.AbstractHttpMiddleware=class AbstractHttpMiddleware{}},767:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractHttpRequestHandler=void 0;const n=i(2318),r=i(9202),s=i(6004);t.AbstractHttpRequestHandler=class AbstractHttpRequestHandler{constructor(e,t){this.mountPoint=e,this.logger=t}resolverMountPoint(e,t){if(!e)return"";const i=[];return i.push(...t),i.reduce(((e,t)=>`${e}/${t}`),"").replace(/(\/)\/+/g,"$1")}getMountedEndpointInfo(){var e,t,i;return o(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const o=[],a=(0,n.getServiceProvider)().getInjector(),d=a.resolveMultiple(s.AbstractHttpController);yield a.initInstances();for(const e of d){const t=(0,n.getObjectMetadata)(e.constructor),i=e.getEndpointMetadata();for(const r of i){const i={mount:r.httpMethod===n.SocketMethod.MESSAGE?r.url:this.resolverMountPoint(t,[this.mountPoint||"/",r.url]),httpMethod:r.httpMethod,controller:e,handlerFunctionName:r.name};o.push({endpointMetadata:r,endpoint:i})}}const l=[];for(const n of o){const o=l.find((e=>e.endpoint.mount===n.endpoint.mount&&e.endpoint.httpMethod===n.endpoint.httpMethod));o?null===(e=this.logger)||void 0===e||e.warn(`Implicit overriding endpoint: ${(0,r.getEndpointId)(o.endpoint)} of ${null===(t=o.endpoint.controller)||void 0===t?void 0:t.constructor.name}:${o.endpoint.handlerFunctionName}`,`Ignore ${(0,r.getEndpointId)(n.endpoint)} of ${null===(i=n.endpoint.controller)||void 0===i?void 0:i.constructor.name}:${n.endpoint.handlerFunctionName}`):l.push(n)}this.mountedEndpointInfo=l}return this.mountedEndpointInfo}))}}},7282:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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(i,o){t(i,o,e)}},s=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},a=this&&this.__rest||function(e,t){var i={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++)t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}return i};Object.defineProperty(t,"__esModule",{value:!0}),t.CrudHttpController=void 0;const d=i(2318),l=i(7756),c=i(1532),u=i(8903),p=i(4638),h=i(2417),f=i(6004),v=i(3198),y=i(1071);class CrudHttpController extends f.AbstractHttpController{constructor(e,t,i){super(i),this.model=e,this.crudRepository=t,this.databaseAdapter=i,this.modelMetadata=(0,d.getObjectMetadata)(e)}getMountedUrl(){return`/${this.model.name.toLowerCase()}`}getAuthProvider(){return s(this,void 0,void 0,(function*(){if(void 0===this.principalResolver){const e=(0,d.getServiceProvider)().getInjector();this.principalResolver=e.resolveOptional(p.AbstractPrincipalResolver)||null,yield e.initInstances()}return this.principalResolver}))}createManyEndpoinMetadata(){const e={};return e.httpMethod=d.HttpMethod.POST,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.createMany.name,e.displayName="createMany"+this.model.name,e.bodyValidationDto=(0,d.getCreateManyBodyValidator)(this.modelMetadata),e.responseValidationDto=(0,d.getCreateManyResponseValidator)(this.modelMetadata),e.accessConditions=[],e.params={0:{source:"raw"}},e}getManyEndpointMetadata(){const e={};return e.httpMethod=d.HttpMethod.GET,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.getMany.name,e.displayName="getAll"+this.model.name,e.queriesValidationDto=(0,d.getGetManyQueryValidator)(this.modelMetadata),e.responseValidationDto=(0,d.getGetManyResponseValidator)(this.modelMetadata),e.accessConditions=[(0,y.FilterModelFieldAccessCondition)(this.model,"model_projection",(e=>e.getQuery().projection)),v.MaximumQueryLimit],e.params={0:{source:"raw"}},e}updateManyEndpointMetadata(){const e={};return e.httpMethod=d.HttpMethod.PUT,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.updateMany.name,e.displayName="update"+this.model.name,e.queriesValidationDto=(0,d.getUpdateManyQueryValidator)(this.modelMetadata),e.bodyValidationDto=(0,d.getUpdateManyBodyValidator)(this.modelMetadata),e.responseValidationDto=(0,d.getUpdateManyResponseValidator)(this.modelMetadata),e.accessConditions=[(0,y.FilterModelFieldAccessCondition)(this.model,"restrict_update_fields",(e=>{const t=e.getBody().update;return t?Object.keys((0,d.leanData)(t)):[]}))],e.params={0:{source:"raw"}},e}updateRecordsEndpointMetadata(){const e={};return e.httpMethod=d.HttpMethod.PUT,e.url=`${this.getMountedUrl()}/records`,e.name=CrudHttpController.prototype.updateRecords.name,e.displayName="updateRecords"+this.model.name,e.queriesValidationDto=(0,d.getUpdateRecordsQueryValidator)(),e.bodyValidationDto=(0,d.getUpdateRecordsBodyValidator)(this.modelMetadata),e.responseValidationDto=(0,d.getUpdateManyResponseValidator)(this.modelMetadata),e.accessConditions=[(0,y.FilterModelFieldAccessCondition)(this.model,"restrict_update_fields",(e=>e.getBody().records.flatMap((e=>{var{id:t}=e,i=a(e,["id"]);return Object.keys((0,d.leanData)(i)||{})})).reduce(d.uniqueReducer,[])))],e}deleteManyEndpoinMetadata(){const e={};return e.httpMethod=d.HttpMethod.DEL,e.url=this.getMountedUrl(),e.name=CrudHttpController.prototype.deleteMany.name,e.displayName="delete"+this.model.name,e.queriesValidationDto=(0,d.getUpdateManyQueryValidator)(this.modelMetadata),e.responseValidationDto=(0,d.getUpdateManyResponseValidator)(this.modelMetadata),e.params={0:{source:"raw"}},e.accessConditions=[],e}getEndpointMetadata(){var e,t,i,o;let n=super.getEndpointMetadata();const r=[];(null===(e=this.modelMetadata.ignoreCrud)||void 0===e?void 0:e.includes(d.HttpMethod.GET))?n=n.filter((e=>e.name!==CrudHttpController.prototype.getMany.name)):r.push(this.getManyEndpointMetadata()),(null===(t=this.modelMetadata.ignoreCrud)||void 0===t?void 0:t.includes(d.HttpMethod.POST))?n=n.filter((e=>e.name!==CrudHttpController.prototype.createMany.name)):r.push(this.createManyEndpoinMetadata()),(null===(i=this.modelMetadata.ignoreCrud)||void 0===i?void 0:i.includes(d.HttpMethod.PUT))?n=n.filter((e=>e.name!==CrudHttpController.prototype.updateMany.name)):(r.push(this.updateManyEndpointMetadata()),r.push(this.updateRecordsEndpointMetadata())),(null===(o=this.modelMetadata.ignoreCrud)||void 0===o?void 0:o.includes(d.HttpMethod.DEL))?n=n.filter((e=>e.name!==CrudHttpController.prototype.deleteMany.name)):r.push(this.deleteManyEndpoinMetadata());for(const e of r){const t=n.findIndex((t=>t.httpMethod===e.httpMethod&&t.url===e.url||t.name===e.name&&(!t.httpMethod||!t.url)));t>=0?n[t]=Object.assign(Object.assign(Object.assign({},e),n[t]),{accessConditions:[...e.accessConditions||[],...n[t].accessConditions||[]]}):n.push(e)}return n}updateRecords(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),i=yield this.getAuthProvider(),o=i&&(yield i.resolvePrincipal(e)),n=e.getBody(),r=e.getQuery(),s={modified:(yield Promise.all(n.records.map((e=>this.crudRepository.updateMany({principal:o,queries:Object.assign(Object.assign({},r),{fields:{id:[e.id]}}),body:{update:(0,d.omitData)(e,["id"])},tx:t}))))).map((e=>e.modified[0]))};return u.ResponseBuilder.json(s).get()}))}createMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),i=yield this.getAuthProvider(),o=i&&(yield i.resolvePrincipal(e)),n=yield this.crudRepository.createMany({principal:o,body:e.getBody(),tx:t});return u.ResponseBuilder.json(n).get()}))}getMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.crudRepository.getMany({queries:e.getQuery(),queryProvider:this.databaseAdapter});return u.ResponseBuilder.json(t).get()}))}updateMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),i=yield this.getAuthProvider(),o=i&&(yield i.resolvePrincipal(e)),n=yield this.crudRepository.updateMany({principal:o,queries:e.getQuery(),body:e.getBody(),tx:t});return u.ResponseBuilder.json(n).get()}))}deleteMany(e){return s(this,void 0,void 0,(function*(){const t=yield this.getCurrentTransaction(),i=yield this.crudRepository.deleteMany({queries:e.getQuery(),tx:t});return u.ResponseBuilder.json({modified:i.modified.map((e=>e.id)).map((e=>({id:e})))}).get()}))}}o([(0,l.Transactional)(l.PropagationMode.INHERIT_OR_CREATE),(0,h.ApiDescription)("Update records of this table."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),n("design:type",Function),n("design:paramtypes",[c.HttpRequest]),n("design:returntype",Promise)],CrudHttpController.prototype,"updateRecords",null),o([(0,l.Transactional)(l.PropagationMode.INHERIT_OR_CREATE),(0,h.ApiDescription)("Create records of this table."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),n("design:type",Function),n("design:paramtypes",[c.HttpRequest]),n("design:returntype",Promise)],CrudHttpController.prototype,"createMany",null),o([(0,h.AccessCondition)([]),(0,h.ApiDescription)("Get records of this table."),r(0,(0,h.Raw)()),n("design:type",Function),n("design:paramtypes",[c.HttpRequest]),n("design:returntype",Promise)],CrudHttpController.prototype,"getMany",null),o([(0,l.Transactional)(l.PropagationMode.INHERIT_OR_CREATE),(0,h.ApiDescription)("Find and update records which match search condition."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),n("design:type",Function),n("design:paramtypes",[c.HttpRequest]),n("design:returntype",Promise)],CrudHttpController.prototype,"updateMany",null),o([(0,l.Transactional)(l.PropagationMode.INHERIT_OR_CREATE),(0,h.ApiDescription)("Find and remove records which match search condition."),(0,h.AccessCondition)([]),r(0,(0,h.Raw)()),n("design:type",Function),n("design:paramtypes",[c.HttpRequest]),n("design:returntype",Promise)],CrudHttpController.prototype,"deleteMany",null),t.CrudHttpController=CrudHttpController},5879:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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=i(2318),d=s(i(7325)),l=s(i(9215)),c=i(99),u=s(i(9103)),p=i(8903),h=i(4638),f=i(1532),v=i(5709),y=i(225),g=i(767);let m=class DefaultHttpRequestHandler extends g.AbstractHttpRequestHandler{constructor(e,t,i){super("",e),this.logger=e,this.authorizationProvider=t,this.principalResolver=i,this._middleware=null}handleRequest(e,t){return r(this,void 0,void 0,(function*(){const i=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.headers;case"raw":return t}})),o=yield e.endpoint.controller[e.endpointMetadata.name](...i);return e.endpointMetadata.responseValidationDto&&(o.value=(0,a.stripData)(o.value,e.endpointMetadata.responseValidationDto)),o}))}exit(){}getResponse(e){return r(this,void 0,void 0,(function*(){let t=new p.HttpResponse;const i=e.method,o=(0,l.default)({url:e.fullPath});let n={};const r=(yield this.getMountedEndpointInfo()).find((e=>{const t=e.endpointMetadata.httpMethod===i&&(0,c.match)(e.endpointMetadata.url,{decode:decodeURIComponent})(o.pathname||"/");return!!t&&(n=t,!0)}));if(!r)throw this.logger.debug(e),a.Errors.NOT_FOUND("Handler not found");const s=new f.HttpRequest({clientIP:e.clientIP,method:i,headers:e.headers,pathName:o.pathname||"",hash:o.hash||"",query:u.default.parse(decodeURIComponent(o.search||"")),params:n.params,body:e.body,cookies:e.cookies},r.endpointMetadata),d=yield this.principalResolver.resolvePrincipal(s);s.setAuthInfo(d),r.endpointMetadata.openAccess||(yield this.authorizationProvider.authorize(s,r));const h=yield this.getMiddleware();for(const e of h){if(!(yield e.intercept(s,t,r.endpointMetadata)))return t}const v=yield this.handleRequest(r,s);return v.code=v.code||t.code||200,v.value=v.value||t.value,v.headers=Object.assign(Object.assign({},t.headers),v.headers),v.cookies=Object.assign(Object.assign({},t.cookies),v.cookies),v}))}handle(e){return r(this,void 0,void 0,(function*(){const t=d.default.generate();this.logger.info(`===== HANDLING REQUEST: ${t} - ${e.method}:${e.fullPath}`);try{const i=yield this.getResponse(e);if(!(i&&i instanceof p.HttpResponse))throw a.Errors.SYSTEM_ERROR(`Invalid response value returned, required instance of ${p.HttpResponse.name}, found ${i?null==i?void 0:i.constructor.name:i}`);return this.logger.info(`===== REQUEST SUCCESS: ${t} - ${e.method}:${e.fullPath}`),i}catch(i){this.logger.error(i);const o=p.ResponseBuilder.json({name:i.name,message:i.message}).status(i.code||500).get();return this.logger.info(`===== REQUEST FAILED: ${t} - ${e.method}:${e.fullPath}, code: ${o.code}`,o.value),o}}))}getMiddleware(){return r(this,void 0,void 0,(function*(){if(null===this._middleware){const e=(0,a.getServiceProvider)().getInjector();this._middleware=e.resolveMultiple(y.AbstractHttpMiddleware),yield e.initInstances()}return this._middleware}))}};m=o([(0,a.Injectable)(),(0,a.LogContext)(),n("design:paramtypes",[a.AbstractLogger,v.AbstractRequestAuthorizer,h.AbstractPrincipalResolver])],m),t.DefaultHttpRequestHandler=m},2417:(e,t,i)=>{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.Head=t.Get=t.Del=t.Put=t.Post=t.Endpoint=t.ApiDescription=void 0;const o=i(2318);t.ApiDescription=e=>(t,i)=>{(0,o.initFieldMetadata)(t,i).description=e};t.Endpoint=e=>(t,i)=>{const n=(0,o.initFieldMetadata)(t,i);n.httpMethod=e.method,n.url=e.url||"/"};const HttpMethodDecoratorFactory=e=>i=>(o,n,r)=>(0,t.Endpoint)({method:e,url:i})(o,n);t.Post=HttpMethodDecoratorFactory(o.HttpMethod.POST),t.Put=HttpMethodDecoratorFactory(o.HttpMethod.PUT),t.Del=HttpMethodDecoratorFactory(o.HttpMethod.DEL),t.Get=HttpMethodDecoratorFactory(o.HttpMethod.GET),t.Head=HttpMethodDecoratorFactory(o.HttpMethod.HEAD);t.ApiResponse=e=>(t,i,n)=>{const r=(0,o.initFieldMetadata)(t,i);e===String?r.responseValidationDto={id:"",primitiveType:o.DataType.STRING,fields:[]}:e===Number?r.responseValidationDto={id:"",primitiveType:o.DataType.NUMBER,fields:[]}:e===Boolean?r.responseValidationDto={id:"",primitiveType:o.DataType.BOOLEAN,fields:[]}:r.responseValidationDto=(0,o.getObjectMetadata)(e)};t.OpenAccess=()=>(e,t)=>{(0,o.initFieldMetadata)(e,t).openAccess=!0};t.TfaRequired=()=>(e,t)=>{(0,o.initFieldMetadata)(e,t).tfaRequired=!0};t.AccessCondition=e=>(t,i)=>{(0,o.initFieldMetadata)(t,i).accessConditions=e};const RequestDeco=e=>(t,i,n)=>{const r=(0,o.initFieldMetadata)(t,i),s=Reflect.getMetadata("design:paramtypes",t,i)||[];switch(e){case"body":r.bodyValidationDto=(0,o.getObjectMetadata)(s[n]);break;case"params":r.paramsValidationDto=(0,o.getObjectMetadata)(s[n]);break;case"queries":r.queriesValidationDto=(0,o.getObjectMetadata)(s[n])}r.params||(r.params={}),r.params[n]={source:e,diClass:s[n]}};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,i)=>{(0,o.initFieldMetadata)(t,i).uriMapper=e};t.CurrentUser=e=>(t,i)=>{const n=(0,o.initFieldMetadata)(t,i);n.userResolver=e,n.serverValue=!0}},6507:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileUploadHandler=void 0;t.AbstractFileUploadHandler=class AbstractFileUploadHandler{}},4839:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FileUploadHandler=void 0;const s=i(2318),a=i(7179),d=i(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([{fromURI:e,toURI:t}])}))}copyFile(e,t){return r(this,void 0,void 0,(function*(){yield this.fileService.copyObject([{fromURI:e,toURI: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(yield this.fileService.getAccessUrls([e],!0))[0]}))}resolvePrivateUrl(e){return r(this,void 0,void 0,(function*(){return(yield this.fileService.getAccessUrls([e],!1))[0]}))}};l=o([(0,s.Injectable)(),n("design:paramtypes",[a.AbstractFileService])],l),t.FileUploadHandler=l},5232:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},5048:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractRepository=void 0;const n=i(2318);t.AbstractRepository=class AbstractRepository{constructor(e){this.model=e,this.modelMetadata=(0,n.getObjectMetadata)(this.model)}beforeCreating(e,t){return o(this,void 0,void 0,(function*(){for(const i of t)for(const t of this.modelMetadata.fields)t.userResolver&&e&&(i[t.name]=t.userResolver(e))}))}project(e,t){return t?e.map((e=>t.reduce(((t,i)=>Object.assign(t,{[i]:e[i]})),{}))):e}}},9073:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.DtoRepository=t.MultipleMap=t.SingleMap=void 0;const n=i(2318),r=i(5048),s=i(3355);t.SingleMap=(e,t,i,o,n)=>({multiple:!1,modelClass:e,forwardOps:t,forwardMapping:e=>{const t=i(e[0]||{});return t&&[t]},rootMapping:e=>{const t=e&&e[0];return o(t)},nestedMapping:n});t.MultipleMap=(e,t,i,o,n)=>({multiple:!0,modelClass:e,forwardOps:t,forwardMapping:i,rootMapping:o,nestedMapping:n});class DtoRepository extends r.AbstractRepository{constructor(e,t){super(e),this.model=e,this.dissolver=t}getMapValue(e,t,i,r,s){return o(this,void 0,void 0,(function*(){for(const o of i){const i=yield t(o);let a=r?yield r(o,o.forwardMapping(i),i):o.forwardMapping(i);if(o.nestedMapping&&a)for(const i of a)yield this.getMapValue(e,t,o.nestedMapping(i),r,s);s&&(a=yield s(o,o.forwardMapping(i),i));const d=o.rootMapping(a);(0,n.deepMerge)(e,d)}}))}createMany({principal:e,body:t,tx:i}){return o(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=>o(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({ops:e.forwardOps(),queryProvider:i})).records}))),this.dissolver(a),((t,r,a)=>o(this,void 0,void 0,(function*(){if(!r)return[];const o=new s.ModelRepository(t.modelClass),d=t.forwardOps();if(t.multiple){yield o.deleteMany({ops:d,tx:i});return(yield o.createMany({principal:e,body:{records:r},tx:i})).records}{const s=r[0];if(!s)return[];if(0===a.length){return(yield o.createMany({principal:e,body:{records:r},tx:i})).records}if(1===a.length){const t=yield o.updateMany({principal:e,ops:d,body:{update:s},tx:i});return[Object.assign(Object.assign(Object.assign({},a[0]),s),t.modified[0])]}throw n.Errors.VALIDATION_ERROR(`Found multiple record when creating ${t.modelClass.name}`)}})))),r.push(a);return{records:r}}))}updateMany({principal:e,queries:t,ops:i,body:r,tx:a}){var d;return o(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 n.Errors.VALIDATION_ERROR("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=>o(this,void 0,void 0,(function*(){const t=new s.ModelRepository(e.modelClass);return(yield t.getMany({ops:e.forwardOps(i),queryProvider:a})).records}))),this.dissolver(l),((t,n,r)=>o(this,void 0,void 0,(function*(){if(!n)return[];const o=new s.ModelRepository(t.modelClass),d=t.forwardOps(i);if(t.multiple){yield o.deleteMany({ops:d,tx:a});return(yield o.createMany({principal:e,body:{records:n},tx:a})).records}{const t=n[0];return t?0==r.length?[]:(r.length>1?(yield o.deleteMany({ops:d,tx:a}),yield o.createMany({principal:e,body:{records:[t]},tx:a})):yield o.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:i}){var r;return o(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 n.Errors.VALIDATION_ERROR("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>o(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),(e=>o(this,void 0,void 0,(function*(){const o=new s.ModelRepository(e.modelClass);return(yield o.getMany({ops:e.forwardOps(t),queryProvider:i})).records})))),a.id?{records:this.project([a],e.projection),total:1}:{records:[],total:0}}))}deleteMany({queries:e,ops:t,tx:i}){var r;return o(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 n.Errors.VALIDATION_ERROR("Missing required id field in query");const a={id:e.fields.id[0]};return yield this.getMapValue(a,(()=>o(this,void 0,void 0,(function*(){return[]}))),this.dissolver(a),void 0,(n=>o(this,void 0,void 0,(function*(){const o=new s.ModelRepository(n.modelClass),r=n.forwardOps(t);return(yield o.deleteMany({queries:{returning:null==e?void 0:e.returning},ops:r,tx:i})).modified})))),{modified:a.id?[a]:[]}}))}}t.DtoRepository=DtoRepository},8023:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},3355:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ModelRepository=void 0;const n=i(2318),r=i(7756),s=i(6507),a=i(5048),d=i(2552),l=i(5481);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 i=t.hasMany.relationDto,o=this.getRequestQueryConditionFromQuery(null==e?void 0:e.fields[t.name],Object.assign(Object.assign({},i),{fields:i.fields.filter((e=>{var i;return e.name!==(null===(i=t.hasMany)||void 0===i?void 0:i.column)}))}));return{modelId:t.hasMany.relationDto.id,targetField:t.hasMany.column,queries:o.length?{_and:o}:{}}}))}getUploadHandler(){return o(this,void 0,void 0,(function*(){if(void 0===this.fileUploadHandler){const e=(0,n.getServiceProvider)().getInjector();this.fileUploadHandler=e.resolveOptional(s.AbstractFileUploadHandler)||null,yield e.initInstances()}return this.fileUploadHandler}))}getRequestQueryConditionFromQuery(e,t){var i;const o=[];for(const s of(0,r.getDirectFields)(t)){const r=`${t.id}.${s.name}`,a=e[s.name];if(void 0!==a)if(s.pk||s.fk||s.isSymbol)o.push({_in:{[r]:a}});else if(s.enum)o.push({_in:{[r]:a}});else switch(s.dataType){case n.DataType.STRING:if(s.searchable){const e={[(null==s?void 0:s.searchable.caseSensitive)?(null==s?void 0:s.searchable.accentSensitive)?"_sub":"_usub":(null===(i=null==s?void 0:s.searchable)||void 0===i?void 0:i.accentSensitive)?"_isub":"_iusub"]:{[r]:a}};o.push(e)}else o.push({_eq:{[r]:a}});break;case n.DataType.NUMBER:const e=new n.RangeQueryDto;Object.assign(e,a),e.min&&(e.minExclusive?o.push({_gt:{[r]:e.min}}):o.push({_gte:{[r]:e.min}})),e.max&&(e.maxExclusive?o.push({_lt:{[r]:e.max}}):o.push({_lte:{[r]:e.max}}));break;case n.DataType.BOOLEAN:o.push({_eq:{[r]:a}})}}return o}uriHandling(e){var t,i;return o(this,void 0,void 0,(function*(){const r=[],s=yield this.getUploadHandler(),a=[],uriHandler=(e,t,i,n)=>o(this,void 0,void 0,(function*(){const o=t(e,i);o&&(yield s.copyFile(e,o),n(o))}));if(s)for(const o of this.modelMetadata.fields)for(const s of e)if(o.uriMapper){const e=s[o.name];if(!e)continue;(null===(t=o.mimeProps)||void 0===t?void 0:t.keepOnRemove)||r.push(e),a.push(uriHandler(e,o.uriMapper,(0,n.getSystemLocale)(),(e=>s[o.name]=e)))}else if(o.multiLocaleColumn){const e=this.modelMetadata.fields.find((e=>e.name===o.multiLocaleColumn));if((null==e?void 0:e.uriMapper)&&s[o.name]){const t=Object.keys(s[o.name]).map((e=>[e,s[o.name][e]]));for(const n of t)(null===(i=e.mimeProps)||void 0===i?void 0:i.keepOnRemove)||r.push(n[1]),a.push(uriHandler(n[1],e.uriMapper,n[0],(e=>s[o.name][n[0]]=e)))}}return yield Promise.all(a),()=>o(this,void 0,void 0,(function*(){s&&(yield Promise.all(r.map((e=>s.removeFile(e)))))}))}))}beforeReturning(e){return o(this,void 0,void 0,(function*(){const t=yield this.getUploadHandler();if(!t)return;const i=[];for(const n of e)for(const e of this.modelMetadata.fields)if(e.uriMapper){if(!n[e.name])continue;i.push((()=>o(this,void 0,void 0,(function*(){var i;n[e.name]=(null===(i=e.mimeProps)||void 0===i?void 0:i.public)?yield t.resolvePublicUrl(n[e.name]):yield t.resolvePrivateUrl(n[e.name])})))())}else if(e.multiLocaleColumn){const r=this.modelMetadata.fields.find((t=>t.name===e.multiLocaleColumn));if(null==r?void 0:r.uriMapper){const s=n[e.name];if(!s)continue;for(const e of Object.keys(s))i.push((()=>o(this,void 0,void 0,(function*(){var i;s[e]=(null===(i=r.mimeProps)||void 0===i?void 0:i.public)?yield t.resolvePublicUrl(s[e]):yield t.resolvePrivateUrl(s[e])})))())}}yield Promise.all(i)}))}createMany({principal:e,body:t,tx:i}){var s;return o(this,void 0,void 0,(function*(){const o=t.records;if(!o.length)return{records:[]};const a=(0,r.getDirectFields)(this.modelMetadata),c=a.filter((e=>!!e.multiLocaleColumn)),u=yield this.uriHandling(o),p=(0,n.getSystemLocale)();if(p)for(const e of o)for(const t of c)e[t.name]&&(e[t.multiLocaleColumn]=e[t.name][p]);const h=o.map(((e,t)=>c.filter((t=>!!e[t.name])).map((e=>({recordIndex:t,field:e.name,entryObject:{}}))))).flatMap((e=>e)),f=yield i.use(l.LocaleEntry).createMany(h.map((e=>e.entryObject))),v=o.map((e=>c.filter((t=>!!e[t.name])).map((t=>e[t.name])))).flatMap((e=>e)).map(((e,t)=>Object.keys(e).map((i=>({localeCode:i,entryId:f[t].id,translation:e[i]}))))).flatMap((e=>e));yield i.use(d.LocaleTranslation).createMany(v),t.records=o.map(((e,t)=>a.reduce(((i,o)=>{let n=e[o.name];if(o.multiLocaleColumn){const e=h.findIndex((e=>e.recordIndex===t&&e.field===o.name));e>=0&&(n=f[e].id)}return Object.assign(i,void 0!==n?{[o.name]:n}:{})}),{}))),yield this.beforeCreating(e,t.records);let y=t.records.length?yield i.use(this.model).createMany(t.records):[];yield this.beforeReturning(y);const g=this.modelMetadata.fields.filter((e=>!e.multiLocaleColumn&&(e.pk||e.serverValue||e.mimeProps))).map((e=>e.name));y=this.project(y,g);const m=this.modelMetadata.fields.filter((e=>!!e.hasMany));for(const r of m){const a=y.flatMap(((e,t)=>{var i;const n=o[t][r.name];return n?((null===(i=r.hasMany)||void 0===i?void 0:i.single)?[n]:n).map((t=>Object.assign(Object.assign({},t),{[r.hasMany.column]:e.id}))):[]}));if(a.length){const o=new ModelRepository((0,n.getModelById)(r.hasMany.relationDto.id));t.records=a;const d=yield o.createMany({principal:e,body:t,tx:i});for(let e=0;e<d.records.length;e++)a[e]=Object.assign(Object.assign({},a[e]),d.records[e]);for(let e=0;e<y.length;e++){const t=[];for(let i=0;i<a.length;i++)a[i][r.hasMany.column]===y[e].id&&t.push(d.records[i]);y[e]=Object.assign(Object.assign({},y[e]),{[r.name]:(null===(s=r.hasMany)||void 0===s?void 0:s.single)?t[0]:t})}}}return yield u(),{records:y}}))}updateMany({principal:e,ops:t,queries:i,body:s,tx:a}){var c,u;return o(this,void 0,void 0,(function*(){const o=t||[],p=this.modelMetadata.fields.filter((e=>!!e.hasMany)),h=(0,n.getSystemLocale)(),f=(0,r.getDirectFields)(this.modelMetadata).filter((e=>!e.multiLocaleColumn&&(void 0!==s.update[e.name]||e.isMultiLocale&&!!h))),v=Object.keys(s.update),y=this.modelMetadata.fields.filter((e=>v.includes(e.name)&&e.multiLocaleColumn)),g=yield this.uriHandling([s.update]),m=(0,n.leanData)(f.reduce(((e,t)=>Object.assign(e,{[t.name]:s.update[t.name]})),{}))||{};if(h)for(const e of y)if(s.update[e.name]){const t=s.update[e.name][h];void 0!==t&&(m[e.multiLocaleColumn]=t)}if(null==i?void 0:i.fields){const e=this.getRequestQueryConditionFromQuery(i.fields,this.modelMetadata);e.length&&o.push(...e)}const b=o.length?{_and:[...o]}:{},M=this.getNestedQueries(i);let S=[],R=[];if(M.length){const e=yield a.use(this.model).getMany(b,{projection:["id"]},M);S=e.records.map((e=>e.id)),S.length&&(R=f.length?yield a.use(this.model).updateMany({_in:{id:S}},m,!0):S.map((e=>({id:e}))))}else if(f.length)R=yield a.use(this.model).updateMany(b,m,!0),S=R.map((e=>e.id));else{const e=yield a.use(this.model).getMany(b,{projection:["id"]});S=e.records.map((e=>e.id)),R=S.map((e=>({id:e})))}const j=R.map((e=>Object.assign(Object.assign({},s.update),e)));if(y.length){const e=yield a.use(this.model).getRecords({_in:{id:S}},{projection:["id",...y.map((e=>e.name))]}),t=e.map((e=>y.filter((t=>!e[t.name])).map((t=>({recordId:e.id,field:t.name}))))).flatMap((e=>e)),i=t.length?yield a.use(l.LocaleEntry).createMany(t.map((()=>({})))):[],o=[];i.forEach(((i,n)=>{const r=t[n],s=e.find((e=>e.id===r.recordId));if(s){s[r.field]=i.id;let e=o.find((e=>e.id===s.id));e||(e={id:s.id},o.push(e)),e[r.field]=i.id}})),yield Promise.all(o.map((e=>a.use(this.model).updateById(e.id,(0,n.omitData)(e,["id"])))));const r=[];for(const t of y){const i=s.update[t.name],o=Object.keys(i||{}).filter((e=>e!==h));o.length&&r.push(...e.map((e=>o.map((o=>({entryId:e[t.name],langCode:o,translation:i[o]}))))).flatMap((e=>e)))}r.length&&(yield a.use(d.LocaleTranslation).deleteMany({_or:r.map((e=>({_eq:{entryId:e.entryId,localeCode:e.langCode}})))}),yield a.use(d.LocaleTranslation).createMany(r.map((e=>({entryId:e.entryId,localeCode:e.langCode,translation:e.translation})))))}for(const t of p){const i=s.update[t.name];if(void 0===i||!S.length)continue;if(S.length>1)throw n.Errors.SYSTEM_ERROR(`Multiple records found while updating @HasMany field: ${t.name}`);const o=j.find((e=>e.id===S[0])),r=(0,n.getModelById)(t.hasMany.relationDto.id),d=a.use(r),l=(yield d.getRecords({_eq:{[t.hasMany.column]:o.id}},{limit:(null===(c=t.hasMany)||void 0===c?void 0:c.single)?1:void 0})).map((e=>e.id)),p=i.map((e=>e.id)).filter((e=>!!e)),h=l.filter((e=>!p.includes(e))),f=i.filter((e=>!e.id)).map((e=>Object.assign(Object.assign({},e),{[t.hasMany.column]:o.id}))),v=i.filter((e=>!!e.id));h.length&&(yield d.deleteMany({_in:{id:h}}));const y=new ModelRepository(r),g=yield y.createMany({principal:e,body:{records:f},tx:a}),m=yield Promise.all(v.filter((e=>Object.keys(e).length>1)).map((t=>y.updateMany({queries:{returning:!0},principal:e,ops:[{_eq:{id:t.id}}],tx:a,body:{update:(0,n.leanData)(Object.assign(Object.assign({},t),{id:void 0}))}})))),b=f.map(((e,t)=>Object.assign(Object.assign({},e),g.records[t]))).concat(m.map((e=>e.modified[0])));o[t.name]=(null===(u=t.hasMany)||void 0===u?void 0:u.single)?b[0]:b}let C=["id"];return(null==i?void 0:i.returning)&&(C=[...C,...Object.keys(s.update).filter((e=>void 0!==s.update[e])),"lastModified"]),yield g(),yield this.beforeReturning(j),{modified:this.project(j,C)}}))}getMany({queries:e,ops:t,queryProvider:i}){var r;return o(this,void 0,void 0,(function*(){const o=t||[];if((null==e?void 0:e.fields)&&o.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&&o.push({_or:t})}const s=this.modelMetadata.fields.filter((t=>t.isMultiLocale&&(!(null==e?void 0:e.projection)||e.projection.includes(t.name)))),a=this.modelMetadata.fields.filter((e=>s.find((t=>t.name===e.multiLocaleColumn)))),l=(null==e?void 0:e.projection)&&[...e.projection.filter((e=>!this.modelMetadata.fields.find((t=>t.name===e&&!!t.hasMany)))),...a.map((e=>e.name))],c=yield i.use(this.model).getMany(o.length?{_and:o}:{},{limit:null==e?void 0:e.limit,page:null==e?void 0:e.page,projection:l,order:"random"===(null==e?void 0:e.order)?e.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)),u=c.records.map((e=>e.id)),p=c.records.map((e=>a.map((t=>e[t.name])))).flatMap((e=>e)).filter((e=>e)),h=(0,n.getSystemLocale)(),f=p.length?(null==e?void 0:e.locale)?e.locale.toLowerCase()!==h?yield i.use(d.LocaleTranslation).getRecords({_in:{entryId:p},_eq:{localeCode:e.locale}},{projection:["entryId","localeCode","translation"]}):[]:yield i.use(d.LocaleTranslation).getRecords({_in:{entryId:p}},{projection:["entryId","localeCode","translation"]}):[];for(const t of c.records)for(const i of a)if(null==e?void 0:e.locale){const o=f.find((o=>o.localeCode===e.locale&&o.entryId===t[i.name]));o&&(t[i.multiLocaleColumn]=o.translation)}else{const e=f.filter((e=>e.entryId===t[i.name]));e.length?t[i.name]=e.reduce(((e,t)=>Object.assign(e,{[t.localeCode]:t.translation})),{}):t[i.name]={}}for(const t of this.modelMetadata.fields){if(!t.hasMany||(null==e?void 0:e.projection)&&!e.projection.includes(t.name))continue;const o=(0,n.getModelById)(t.hasMany.relationDto.id),r=new ModelRepository(o),s=u.length?yield r.getMany({queries:{fields:{[t.hasMany.column]:u},limit:t.hasMany.single?1:0},queryProvider:i}):{records:[]};for(const e of c.records){const i=s.records.filter((i=>i[t.hasMany.column]===e.id));e[t.name]=t.hasMany.single?i[0]:i}}return yield this.beforeReturning(c.records),{total:c.total,records:this.project(c.records,(null==e?void 0:e.projection)&&[...e.projection,...e.locale?[]:l||[]].reduce(n.uniqueReducer,[]))}}))}deleteMany({queries:e,ops:t,tx:i}){var n,r;return o(this,void 0,void 0,(function*(){let o=t||[];if(null==e?void 0:e.fields){const t=this.getRequestQueryConditionFromQuery(e.fields,this.modelMetadata);t.length&&o.push(...t)}const s=o.length?{_and:[...o,...t||[]]}:{},a=this.getNestedQueries(e);let c=[];const u=this.modelMetadata.fields.filter((e=>e.uriMapper)),p=this.modelMetadata.fields.filter((e=>e.multiLocaleColumn));if(a.length||p.length||u.length){const e=yield i.use(this.model).getRecords(s,{projection:["id",...[...p,...u].map((e=>e.name))]},a);yield i.use(this.model).deleteMany({_in:{id:e.map((e=>e.id))}});const t=[];for(const i of e)for(const e of u)i[e.name]&&!(null===(n=e.mimeProps)||void 0===n?void 0:n.keepOnRemove)&&t.push(i[e.name]);const o=[];for(const t of e)for(const e of p){const i=this.modelMetadata.fields.find((t=>t.name===e.name));(null==i?void 0:i.uriMapper)&&!(null===(r=i.mimeProps)||void 0===r?void 0:r.keepOnRemove)&&t[i.name]&&o.push(t[i.name])}if(o.length){const e=yield i.use(d.LocaleTranslation).getRecords({_in:{entryId:o}},{projection:["translation"]});for(const i of e)i.translation&&t.push(i.translation)}const h=e.map((e=>p.map((t=>e[t.name])))).flatMap((e=>e)).filter((e=>!!e));if(h.length&&(yield i.use(l.LocaleEntry).deleteMany({_in:{id:h}})),t.length){const e=yield this.getUploadHandler();e&&(yield Promise.all(t.map((t=>e.removeFile(t)))))}c=e}else c=yield i.use(this.model).deleteMany(s,null==e?void 0:e.returning);return{modified:c}}))}}t.ModelRepository=ModelRepository},2255:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractAccessCondition=void 0;t.AbstractAccessCondition=class AbstractAccessCondition{}},1071:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.FilterModelFieldAccessCondition=void 0;const r=i(2318),s=i(2255);t.FilterModelFieldAccessCondition=(e,t,i)=>{let a=class _ extends s.AbstractAccessCondition{resolveConditionValue(e){return n(this,void 0,void 0,(function*(){return i(e)}))}getConditionMetadata(){return{name:t,valueType:r.AccessConditionValueType.CHOICES,valueConstraint:(0,r.getObjectMetadata)(e).fields.map((e=>e.name))}}validate(e,t){return n(this,void 0,void 0,(function*(){return!!e&&e.every((e=>t.includes(e)))}))}};return a=o([(0,r.Register)()],a),a}},3198:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.MaximumQueryLimit=void 0;const r=i(2318),s=i(2255);let a=class MaximumQueryLimit extends s.AbstractAccessCondition{resolveConditionValue(e){return n(this,void 0,void 0,(function*(){let t=e.getQuery().limit;return t&&(t=parseInt(t)),t||0}))}validate(e,t){return n(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=o([(0,r.Register)()],a),t.MaximumQueryLimit=a},7493:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},9202:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.getApiInfo=t.getEndpointId=void 0;const n=i(2318),r=i(767),s=i(5530);t.getEndpointId=e=>`${e.httpMethod}:${e.mount}`;t.getApiInfo=()=>o(void 0,void 0,void 0,(function*(){const e=(0,n.getServiceProvider)().getInjector(),i=e.resolveOptional(r.AbstractHttpRequestHandler),o=e.resolveOptional(s.AbstractServerSocketManager);yield e.initInstances();return{permissions:[...i?yield i.getMountedEndpointInfo():[],...o?yield o.getMountedEndpointInfo():[]].map((i=>{var o;return{id:(0,t.getEndpointId)(i.endpoint),description:i.endpointMetadata.description,name:i.endpointMetadata.displayName||i.endpointMetadata.name,openAccess:!!i.endpointMetadata.openAccess,permissionGroup:i.endpointMetadata.permissionGroup||"",accessConditions:(null===(o=i.endpointMetadata.accessConditions)||void 0===o?void 0:o.map((t=>e.resolve(t).getConditionMetadata())))||[],readOnly:i.endpointMetadata.httpMethod===n.HttpMethod.GET,tfaRequired:!!i.endpointMetadata.tfaRequired,method:i.endpointMetadata.httpMethod,mount:i.endpoint.mount||"",paramDto:i.endpointMetadata.paramsValidationDto,queryDto:i.endpointMetadata.queriesValidationDto,bodyDto:i.endpointMetadata.bodyValidationDto,responseDto:i.endpointMetadata.responseValidationDto}}))}}))},341:function(e,t,i){var o=this&&this.__createBinding||(Object.create?function(e,t,i,o){void 0===o&&(o=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,o,n)}:function(e,t,i,o){void 0===o&&(o=i),e[o]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||o(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),n(i(9025),t),n(i(4638),t),n(i(1820),t),n(i(1870),t),n(i(4972),t),n(i(4435),t),n(i(7540),t),n(i(8985),t),n(i(2872),t),n(i(7678),t),n(i(8903),t),n(i(2417),t),n(i(1532),t),n(i(5879),t),n(i(6004),t),n(i(7282),t),n(i(767),t),n(i(225),t),n(i(7493),t),n(i(2255),t),n(i(1071),t),n(i(3198),t),n(i(5709),t),n(i(3355),t),n(i(9073),t),n(i(8023),t),n(i(5048),t),n(i(5530),t),n(i(2841),t),n(i(7152),t),n(i(8577),t),n(i(2665),t),n(i(9990),t),n(i(9202),t),n(i(6507),t),n(i(4839),t),n(i(5232),t),n(i(5572),t),n(i(10),t),n(i(5481),t),n(i(2552),t),n(i(889),t),n(i(5537),t),n(i(226),t),n(i(8836),t),n(i(9627),t),n(i(7014),t),n(i(7179),t),n(i(4487),t),n(i(7120),t),n(i(4),t),n(i(6135),t),n(i(4),t),n(i(5991),t),n(i(3912),t),n(i(6135),t),n(i(1786),t),n(i(7380),t),n(i(8037),t),n(i(2345),t),n(i(7724),t),n(i(1556),t),n(i(2363),t),n(i(4683),t),n(i(9527),t),n(i(3376),t),n(i(5033),t),n(i(523),t)},4683:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobController=void 0;const o=i(2318),n=i(5007);class AbstractJobController extends n.Transactionable{getAllJobs(){const e=(0,o.getObjectMetadata)(this.constructor);return(null==e?void 0:e.jobs)||[]}}t.AbstractJobController=AbstractJobController},523:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobRepository=void 0;t.AbstractJobRepository=class AbstractJobRepository{}},9527:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractJobScheduler=void 0;const n=i(2318),r=i(4683);t.AbstractJobScheduler=class AbstractJobScheduler{constructor(e){this.logger=e,this._jobs=null}getAvailableJobInfo(){return o(this,void 0,void 0,(function*(){if(null===this._jobs){const e=(0,n.getServiceProvider)().getInjector(),t=e.resolveMultiple(r.AbstractJobController);yield e.initInstances(),this._jobs=t.flatMap((e=>e.getAllJobs().map((t=>Object.assign(Object.assign({},t),{handlerFn:e[t.handlerName].bind(e)})))))}return this._jobs}))}scheduleJobAt(e){return this.scheduleJob(e)}executeJob(e){return o(this,void 0,void 0,(function*(){const t=(yield this.getAvailableJobInfo()).find((t=>t.jobName===e.jobName));t&&(yield t.handlerFn(...e.params||[])),t&&!e.at||(yield this.removeJob(e.jobId),this.logger.info(t?`Remove one-time job ${e.jobName} at timestamp ${e.at}`:`Remove not found job: ${e.jobName}`))}))}}},3376:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AwsJobScheduler=void 0;const a=i(2318),d=i(9336),l=s(i(1495)),c=i(9527),u=i(2363),gcdBetween=(e,t)=>{const i=e>t?e:t,o=e>t?t:e;if(i<=0||o<=0)return 1;if(i%o==0)return o;{const e=Math.trunc(i/o);return gcdBetween(o,i-o*e)}},gcdOf=(e,t)=>t.length?gcdOf(gcdBetween(e,t[0]),t.slice(1)):e,getWaitExpression=e=>`Wait ${e} seconds`;let p=class AwsJobScheduler extends c.AbstractJobScheduler{constructor(e,t,i,o,n,r,s="default",a="claire-aws-job-",l="one-minute-step-function-trigger"){super(e),this.logger=e,this.redisClient=t,this.uniqueIdKey=i,this.apiLambdaFunctionArn=o,this.stepFunctionName=n,this.iamRoleArn=r,this.eventBusName=s,this.jobNamePrefix=a,this.oneMinuteRule=l,this.eventbridge=new d.EventBridge,this.stepfunctions=new d.StepFunctions({apiVersion:"2016-11-23"})}handleInterval(e){return r(this,void 0,void 0,(function*(){this.logger.debug("Handle interval",e,typeof e);const t=(yield this.getAvailableJobInfo()).filter((t=>t.interval&&e%t.interval==0));yield Promise.all(t.map((e=>this.executeJob(Object.assign(Object.assign({},e),{jobId:e.jobName})))))}))}handleCron(e){return r(this,void 0,void 0,(function*(){this.logger.debug("Handle cron",e),yield this.executeJob(e)}))}generateCronFromTimestamp(e){const t=new Date(e);return[t.getUTCMinutes(),t.getUTCHours(),t.getUTCDate(),t.getUTCMonth(),"?",t.getUTCFullYear()].join(" ")}isActiveScheduler(){return!1}getAllScheduledJobs(){return r(this,void 0,void 0,(function*(){const e=yield this.getAvailableJobInfo(),t=yield this.eventbridge.listRules({EventBusName:this.eventBusName,NamePrefix:this.jobNamePrefix}).promise();return(yield Promise.all((t.Rules||[]).map((e=>r(this,void 0,void 0,(function*(){var t;const i=e.Name,o=null===(t=(yield this.eventbridge.listTargetsByRule({EventBusName:this.eventBusName,Rule:i}).promise()).Targets)||void 0===t?void 0:t.find((e=>e.Id===i));if(!o||!o.Input)return;return JSON.parse(o.Input).requestContext.cronScheduler.data})))))).filter((e=>!!e)).concat(e.filter((e=>e.interval)).map((e=>Object.assign(Object.assign({},e),{jobId:e.jobName}))))}))}scheduleJob(e){return r(this,void 0,void 0,(function*(){if(this.logger.debug("Scheduling job: ",e),e.cron||e.at){const t=yield this.redisClient.incr(this.uniqueIdKey),i=`${this.jobNamePrefix}${t}`,o=e.cron?`${e.cron} *`:this.generateCronFromTimestamp(e.at);return this.logger.debug("Cron expression",o),yield this.eventbridge.putRule({Name:i,Description:`${e.jobName} - ${e.cron||e.at}`,EventBusName:this.eventBusName,ScheduleExpression:`cron(${o})`,State:"ENABLED"}).promise(),yield this.eventbridge.putTargets({Rule:i,Targets:[{Arn:this.apiLambdaFunctionArn,Id:i,Input:JSON.stringify({requestContext:{cronScheduler:{data:Object.assign(Object.assign({},e),{jobId:i})}}})}]}).promise(),i}if(e.interval)return e.jobName;throw a.Errors.SYSTEM_ERROR(`Job does not have time config: ${e.jobName}`)}))}syncJobs(){return r(this,void 0,void 0,(function*(){this.logger.debug("Checking interval scheduler"),yield this.checkIntervalScheduler();const e=yield this.getAllScheduledJobs(),t=yield this.getAvailableJobInfo(),i=e.filter((e=>!t.find((t=>t.jobName===e.jobName))));for(const e of i)this.logger.info(`Removing stale job: ${e.jobName} of id: ${e.jobId}`),yield this.removeJob(e.jobId);i.length&&this.logger.info(`Cleaned up: ${i.length} stale jobs`),this.logger.debug("Remove scheduled cron jobs");const o=e.filter((e=>e.cron));yield Promise.all(o.map((e=>this.removeJob(e.jobId))));const n=t.filter((e=>e.cron||e.interval));this.logger.debug("Scheduling cron & interval jobs");for(const e of n)yield this.scheduleJob({jobName:e.jobName,cron:e.cron,interval:e.interval})}))}removeJob(e){return r(this,void 0,void 0,(function*(){yield this.eventbridge.removeTargets({EventBusName:this.eventBusName,Rule:e,Ids:[e]}).promise(),yield this.eventbridge.deleteRule({EventBusName:this.eventBusName,Name:e}).promise()}))}checkIntervalScheduler(){var e,t;return r(this,void 0,void 0,(function*(){const i=(yield this.getAvailableJobInfo()).filter((e=>e.interval)),o=i.map((e=>e.interval)),[n,r]=((e,t)=>{let i=u.JobInterval.EVERY_30S;t.length&&(i=gcdOf(t[0],t.slice(1)),i<u.JobInterval.EVERY_5S&&(i=u.JobInterval.EVERY_5S));const o=Math.trunc(60/i),n=[];for(let e=0;e<o;e++)n.push(e*i);return[i,`\n {\n "StartAt": "Create items",\n "States": {\n "Create items": {\n "Type": "Pass",\n "Next": "Loop",\n "Result": ${JSON.stringify(n)}\n },\n "Loop": {\n "Type": "Map",\n "End": true,\n "Iterator": {\n "StartAt": "${getWaitExpression(i)}",\n "States": {\n "${getWaitExpression(i)}": {\n "Type": "Wait",\n "Seconds": ${i},\n "Next": "Convert time to request object"\n },\n "Convert time to request object": {\n "Type": "Pass",\n "Next": "Lambda Invoke",\n "Result": {\n "requestContext": {\n "intervalScheduler": {\n "time": "$"\n }\n }\n }\n },\n "Lambda Invoke": {\n "Type": "Task",\n "Resource": "arn:aws:states:::lambda:invoke",\n "Parameters": {\n "Payload.$": "$",\n "FunctionName": "${e}:$LATEST"\n },\n "End": true,\n "OutputPath": "$.Payload"\n }\n }\n },\n "MaxConcurrency": 1\n }\n },\n "Comment": "One minute loop to trigger lambda function"\n }\n `]})(this.apiLambdaFunctionArn,o);this.logger.debug("Listing all state machines");const s=yield this.stepfunctions.listStateMachines({}).promise();let a=null===(e=s.stateMachines.find((e=>e.name.includes(this.stepFunctionName))))||void 0===e?void 0:e.stateMachineArn,d=a;if(a){(yield this.stepfunctions.describeStateMachine({stateMachineArn:a}).promise()).definition.includes(getWaitExpression(n))||(this.logger.debug("Step function definition changed, create new state machine"),d="")}const l=`${this.stepFunctionName}-${n}`;if(!d){this.logger.debug(`Create new step function with interval ${n} seconds`);d=(yield this.stepfunctions.createStateMachine({definition:r,name:l,roleArn:this.iamRoleArn,type:"EXPRESS"}).promise()).stateMachineArn}this.logger.debug("Step function ARNs old / new",a,d),this.logger.debug("Getting one minute rule");const c=yield this.eventbridge.listRules({EventBusName:this.eventBusName,NamePrefix:this.oneMinuteRule}).promise(),p=null===(t=c.Rules)||void 0===t?void 0:t.find((e=>e.Name==this.oneMinuteRule));p||(this.logger.debug("Create new one minute rule"),yield this.eventbridge.putRule({EventBusName:this.eventBusName,Name:this.oneMinuteRule,Description:"One minute trigger function for step function",ScheduleExpression:"rate(1 minute)",State:"ENABLED"}).promise()),this.logger.debug("Adding step function state machine as target"),d!==a&&(a&&(this.logger.debug("Removing old target",a),yield this.eventbridge.removeTargets({EventBusName:this.eventBusName,Rule:this.oneMinuteRule,Ids:[this.stepFunctionName]}).promise(),this.logger.debug("Removing old state machine function"),yield this.stepfunctions.deleteStateMachine({stateMachineArn:a}).promise()),this.logger.debug("Adding new target",d),yield this.eventbridge.putTargets({Rule:this.oneMinuteRule,Targets:[{Arn:d,Id:this.stepFunctionName,RoleArn:this.iamRoleArn}]}).promise()),!i.length&&(null==p?void 0:p.State)?(this.logger.info("No interval job found, disable one minute rule"),yield this.eventbridge.disableRule({EventBusName:this.eventBusName,Name:this.oneMinuteRule}).promise()):(this.logger.info("Interval job found, enable one minute rule"),yield this.eventbridge.enableRule({EventBusName:this.eventBusName,Name:this.oneMinuteRule}).promise())}))}};p=o([(0,a.LogContext)(),n("design:paramtypes",[a.AbstractLogger,l.default,String,String,String,String,Object,Object,Object])],p),t.AwsJobScheduler=p},5033:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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=i(2318),d=s(i(1495)),l=s(i(9896)),c=s(i(7344)),u=i(9527),p=i(523),h=i(9512);var f;!function(e){e.SCHEDULE_JOB="SCHEDULE_JOB",e.REMOVE_JOB="REMOVE_JOB",e.SYNC_JOB="SYNC_JOB",e.NOTIFY="NOTIFY"}(f||(f={}));let v=class LocalJobScheduler extends u.AbstractJobScheduler{constructor(e,t,i,o,n,r,s,a,d=30){super(e),this.logger=e,this.redisClient=t,this.subscribeClient=i,this.jobRepo=o,this.lockMutexKey=n,this.holdMutexKey=r,this.uniqueIdKey=s,this.multiClientChannel=a,this.keyRetentionDurationSecond=d,this.intervals=[],this.isActive=!1,this.notifyResolver={},this.jobHolder={}}sendJob(e,t,i){this.subscribeClient.publish(this.multiClientChannel,JSON.stringify({type:e,messageId:t,data:i}))}processMessage(e,t,i){return r(this,void 0,void 0,(function*(){switch(e){case f.SYNC_JOB:yield this.syncJobs(),this.sendJob(f.NOTIFY,t);break;case f.NOTIFY:const o=this.notifyResolver[t];if(!o)return;o(i);break;case f.SCHEDULE_JOB:if(!this.isActive)return;const n=i,r=yield this.scheduleJobAt(n);this.sendJob(f.NOTIFY,t,r);break;case f.REMOVE_JOB:if(!this.isActive)return;const s=i;yield this.removeJob(s),this.sendJob(f.NOTIFY,t);break;default:this.logger.error(`Not recognize message type ${e}`)}}))}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"))}))}init(){return r(this,void 0,void 0,(function*(){this.logger.debug("LocalJobScheduler init"),this.logger.debug("Listening on multi client channel"),this.redisClient.on("message",((e,t)=>{if(e===this.multiClientChannel){const e=JSON.parse(t);this.processMessage(e.type,e.messageId,e.data).catch((t=>this.logger.error(`Fail to process message, ${e}`,t)))}})),yield this.subscribeClient.subscribe(this.multiClientChannel),this.logger.debug("Try to claim active scheduler");const e=new l.default([this.redisClient]);try{const t=yield e.acquire([this.lockMutexKey],this.keyRetentionDurationSecond);this.isActive=!0,yield this.extendMutexKey(),yield t.release(),this.logger.debug("Being active scheduler"),this.mutexHoldInterval=setInterval((()=>{this.extendMutexKey()}),Math.trunc(1e3*this.keyRetentionDurationSecond/2)+1)}catch(e){this.logger.info("Failed to lock mutex key, ignore",e)}}))}exit(){this.mutexHoldInterval&&(0,h.clearInterval)(this.mutexHoldInterval),this.redisClient.quit(),this.subscribeClient.quit();for(const e of this.intervals)(0,h.clearInterval)(e);this.logger.debug("LocalJobScheduler exit")}isActiveScheduler(){return this.isActive}getAllScheduledJobs(){return r(this,void 0,void 0,(function*(){return Object.values(this.jobHolder).filter((e=>!!(null==e?void 0:e.jobInfo))).map((e=>null==e?void 0:e.jobInfo))}))}syncJobs(){return r(this,void 0,void 0,(function*(){if(!this.isActive){const e=yield this.redisClient.incr(this.uniqueIdKey);return new Promise((t=>{this.notifyResolver[e]=t,this.sendJob(f.SYNC_JOB,e)}))}{const e=yield this.getAvailableJobInfo();for(const t of e)(t.cron||t.interval)&&(yield this.scheduleJob(t));const t=yield this.jobRepo.getJobs();for(const e of t)yield this.scheduleJob(e)}}))}scheduleJob(e){return r(this,void 0,void 0,(function*(){if(this.isActive){if(e.at){const t=yield this.jobRepo.saveJob({jobName:e.jobName,params:e.params,at:e.at}),i=Object.assign(Object.assign({},e),{jobId:t}),o=setTimeout((()=>{this.executeJob(i).catch((e=>this.logger.error(`Error execute job ${i.jobName} with id: ${i.jobId}`,e)))}),new Date(e.at).getTime()-Date.now());return this.jobHolder[t]={jobCanceler:()=>(0,h.clearTimeout)(o),jobInfo:Object.assign(Object.assign({},e),{jobId:t})},t}if(e.interval){const t=e.jobName,i=Object.assign(Object.assign({},e),{jobId:t}),o=setInterval((()=>{this.executeJob(i).catch((e=>this.logger.error(`Error execute job ${i.jobName} with id: ${i.jobId}`,e)))}),e.interval);return this.jobHolder[t]={jobCanceler:()=>(0,h.clearInterval)(o),jobInfo:Object.assign(Object.assign({},e),{jobId:t})},t}if(e.cron){const t=e.jobName,i=Object.assign(Object.assign({},e),{jobId:t}),o=c.default.scheduleJob(e.cron,(()=>{this.executeJob(i).catch((e=>this.logger.error(`Error execute job ${i.jobName} with id: ${i.jobId}`,e)))}));return this.jobHolder[t]={jobCanceler:()=>o.cancel(),jobInfo:Object.assign(Object.assign({},e),{jobId:t})},t}throw a.Errors.SYSTEM_ERROR(`Job does not have time config: ${e.jobName}`)}{const t=yield this.redisClient.incr(this.uniqueIdKey);return new Promise((i=>{this.notifyResolver[t]=i,this.sendJob(f.SCHEDULE_JOB,t,e)}))}}))}removeJob(e){return r(this,void 0,void 0,(function*(){if(this.isActive){const t=this.jobHolder[e];return t&&(t.jobCanceler(),this.jobHolder[e]=void 0),void(yield this.jobRepo.removeJobById(e))}{const t=yield this.redisClient.incr(this.uniqueIdKey);return new Promise((i=>{this.notifyResolver[t]=i,this.sendJob(f.REMOVE_JOB,t,e)}))}}))}};v=o([(0,a.LogContext)(),n("design:paramtypes",[a.AbstractLogger,d.default,d.default,p.AbstractJobRepository,String,String,String,String,Number])],v),t.LocalJobScheduler=v},1556:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CustomJob=t.CronJob=t.IntervalJob=void 0;const o=i(2318);t.IntervalJob=(e,t)=>(i,n)=>{const r=(0,o.initObjectMetadata)(i);r.jobs||(r.jobs=[]),r.jobs.push({jobName:e,interval:t,handlerName:n})};t.CronJob=(e,t)=>(i,n)=>{const r=(0,o.initObjectMetadata)(i);if(r.jobs||(r.jobs=[]),5!==t.split(" ").length)throw o.Errors.SYSTEM_ERROR("Invalid cron expression, expect minute / hour / day / month / day-of-week");r.jobs.push({jobName:e,cron:t,handlerName:n})};t.CustomJob=e=>(t,i)=>{const n=(0,o.initObjectMetadata)(t);n.jobs||(n.jobs=[]),n.jobs.push({jobName:e,handlerName:i})}},2363:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.JobInterval=t.CRON_REQUEST_METHOD=t.INTERVAL_REQUEST_METHOD=void 0,t.INTERVAL_REQUEST_METHOD="interval",t.CRON_REQUEST_METHOD="cron",function(e){e[e.EVERY_5S=5]="EVERY_5S",e[e.EVERY_10S=10]="EVERY_10S",e[e.EVERY_15S=15]="EVERY_15S",e[e.EVERY_20S=20]="EVERY_20S",e[e.EVERY_30S=30]="EVERY_30S"}(t.JobInterval||(t.JobInterval={}))},5572:function(e,t,i){var o,n=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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(i(7147)),l=a(i(1017)),c=i(2318);let u=o=class FileLogMedium{constructor(e){const t=e.separated?o.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 i=this.separated?this.destination[o.levels.indexOf(e)]:0;d.default.appendFileSync(i,t)}};u.levels=Object.values(c.LogLevel),u=o=n([(0,c.Initable)(),r("design:paramtypes",[Object])],u),t.FileLogMedium=u},7179:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractFileService=void 0;const n=i(9025),delay=e=>new Promise((t=>setTimeout(t,e)));t.AbstractFileService=class AbstractFileService{getUploadUrlForTempUri(e){return o(this,void 0,void 0,(function*(){const getPutUrl=()=>o(this,void 0,void 0,(function*(){return(yield this.getPresignedUrl(n.FileOperation.PUT,[e]))[0]})),getDeleteUrl=()=>o(this,void 0,void 0,(function*(){return(yield this.getPresignedUrl(n.FileOperation.DELETE,[e]))[0]}));let t={objectKey:e,putPresignedUrl:yield getPutUrl(),deletePresignedUrl:yield getDeleteUrl()};for(;t.putPresignedUrl.endsWith("/");)yield delay(1e3),t.putPresignedUrl=yield getPutUrl();for(;t.deletePresignedUrl.endsWith("/");)yield delay(1e3),t.deletePresignedUrl=yield getDeleteUrl();return t}))}}},4487:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractMailService=void 0;t.AbstractMailService=class AbstractMailService{}},7014:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractService=void 0;const o=i(5007);class AbstractService extends o.Transactionable{}t.AbstractService=AbstractService},7120:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSmsService=void 0;t.AbstractSmsService=class AbstractSmsService{}},4:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalFileService=void 0;const r=n(i(2167)),s=i(9025),a=i(7179);class LocalFileService extends a.AbstractFileService{constructor(e){super(),this.fileServerUrl=e}getFileSize(e){return o(this,void 0,void 0,(function*(){return Promise.all(e.map((e=>o(this,void 0,void 0,(function*(){var t;return(null===(t=(yield r.default.head(`${this.fileServerUrl}/info?objectKey="/${e}"`)).data)||void 0===t?void 0:t.size)||0})))))}))}getAccessUrls(e,t){return o(this,void 0,void 0,(function*(){return e.map((e=>`${this.fileServerUrl}/${e}`))}))}getPresignedUrl(e,t){return o(this,void 0,void 0,(function*(){return e===s.FileOperation.GET?this.getAccessUrls(t,!0):t.map((e=>`${this.fileServerUrl}/?objectKey="/${e}"`))}))}moveObject(e){return o(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>r.default.post(`${this.fileServerUrl}/`,{from:e.fromURI,to:e.toURI}))))}))}copyObject(e){return o(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>r.default.post(`${this.fileServerUrl}/`,{from:e.fromURI,to:e.toURI,copy:!0}))))}))}removeObject(e){return o(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>r.default.delete(`${this.fileServerUrl}/?objectKey="/${e}"`))))}))}}t.LocalFileService=LocalFileService},5991:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalMailService=void 0;const r=n(i(7147)),s=n(i(1017)),a=i(4487);class LocalMailService extends a.AbstractMailService{constructor(e){super(),this.folderPath=e,r.default.existsSync(this.folderPath)||r.default.mkdirSync(e,{recursive:!0})}send(e){return o(this,void 0,void 0,(function*(){const t=s.default.join(this.folderPath,`${Date.now()}.html`);r.default.writeFileSync(t,`\n From: ${e.sender}\n\n To: ${e.receivers.join(", ")}\n\n Cc: ${(e.cc||[]).join(", ")}\n\n Bcc: ${(e.bcc||[]).join(", ")}\n\n\n Subject: ${e.subject}\n\n Content: ${e.contentType}\n\n ${e.content}\n `.trim())}))}}t.LocalMailService=LocalMailService},3912:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalSmsService=void 0;const r=n(i(7147)),s=n(i(1017)),a=i(7120);class LocalSmsService extends a.AbstractSmsService{constructor(e){super(),this.folderPath=e,r.default.existsSync(this.folderPath)||r.default.mkdirSync(this.folderPath,{recursive:!0})}send(e,t,i){return o(this,void 0,void 0,(function*(){const o=s.default.join(this.folderPath,`${Date.now()}`);r.default.writeFileSync(o,`${e}-${t}: ${i}\n`)}))}}t.LocalSmsService=LocalSmsService},6135:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.S3FileService=void 0;const s=i(2318),a=i(9336),d=i(7179);let l=class S3FileService extends d.AbstractFileService{constructor(e,t){super(),this.config=e,this.logger=t,this.s3Client=new a.S3({signatureVersion:"v4",region:this.config.S3_BUCKET_REGION}),this.cloudfrontSigner=new a.CloudFront.Signer(this.config.CLOUD_FRONT_PUBLIC_KEY_ID,Buffer.from(this.config.CLOUD_FRONT_PRIVATE_KEY_BASE64,"base64").toString())}getFileSize(e){return r(this,void 0,void 0,(function*(){return yield Promise.all(e.map((e=>this.getSingleFileSize(e))))}))}getAccessUrls(e,t){return r(this,void 0,void 0,(function*(){return e.map((e=>this.getSingleAccessUrl(e,t)))}))}getPresignedUrl(e,t){return r(this,void 0,void 0,(function*(){return t.map((t=>this.getSinglePresignedUrl(e,t)))}))}moveObject(e){return r(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>this.moveSingleObject(e.fromURI,e.toURI))))}))}copyObject(e){return r(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>this.copySingleObject(e.fromURI,e.toURI))))}))}removeObject(e){return r(this,void 0,void 0,(function*(){yield Promise.all(e.map((e=>this.removeSingleObject(e))))}))}getSingleFileSize(e){return r(this,void 0,void 0,(function*(){return(yield this.s3Client.headObject({Key:e,Bucket:this.config.S3_BUCKET_NAME}).promise().then((e=>e.ContentLength)))||0}))}getSinglePresignedUrl(e,t){return this.cloudfrontSigner.getSignedUrl({url:`${this.config.CLOUD_FRONT_PUBLIC_DOMAIN}/${t}`,expires:Date.now()+36e5})}copySingleObject(e,t){return r(this,void 0,void 0,(function*(){try{yield this.s3Client.copyObject({Bucket:this.config.S3_BUCKET_NAME,CopySource:`/${this.config.S3_BUCKET_NAME}/${e}`,Key:t}).promise()}catch(e){throw this.logger.error(e),e}}))}moveSingleObject(e,t){return r(this,void 0,void 0,(function*(){try{yield this.copySingleObject(e,t),yield this.removeSingleObject(e)}catch(e){throw this.logger.error(e),e}}))}getSingleAccessUrl(e,t){const i=`${this.config.CLOUD_FRONT_PUBLIC_DOMAIN}/${e}`;return t?i:this.cloudfrontSigner.getSignedUrl({url:i,expires:Date.now()+1e3*this.config.PRESIGNED_URL_EXPIRATION_S})}removeSingleObject(e){return r(this,void 0,void 0,(function*(){yield this.s3Client.deleteObject({Bucket:this.config.S3_BUCKET_NAME,Key:e}).promise()}))}};l=o([(0,s.LogContext)(),n("design:paramtypes",[Object,s.AbstractLogger])],l),t.S3FileService=l},1786:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.SesMailService=void 0;const s=i(2318),a=i(9336),d=i(4487);let l=class SesMailService extends d.AbstractMailService{constructor(e,t){super(),this.config=e,this.logger=t,this.emailClient=new a.SES({apiVersion:"2010-12-01",region:this.config.SES_REGION})}send(e){return r(this,void 0,void 0,(function*(){try{const t={Destination:{BccAddresses:e.bcc,CcAddresses:e.cc,ToAddresses:e.receivers},Message:{Body:{},Subject:{Charset:"UTF-8",Data:e.subject}},Source:e.sender};"html"===e.contentType?t.Message.Body.Html={Charset:"UTF-8",Data:e.content}:"text"===e.contentType&&(t.Message.Body.Text={Charset:"UTF-8",Data:e.content}),yield this.emailClient.sendEmail(t).promise()}catch(e){throw this.logger.error(e),s.Errors.SYSTEM_ERROR("Cannot send email")}}))}};l=o([(0,s.LogContext)(),n("design:paramtypes",[Object,s.AbstractLogger])],l),t.SesMailService=l},6862:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocket=void 0;const n=i(2318);t.AbstractServerSocket=class AbstractServerSocket{constructor(e){this.socketInfo=e}getId(){return this.socketInfo.id}getAuthInfo(){return this.socketInfo.authInfo}send(e,t){return o(this,void 0,void 0,(function*(){t?this.socketInfo.channels.find((e=>e.name===t&&e.serverToClientAllowed))&&(yield this.sendRaw({type:n.MessageType.PLAIN,data:{message:e,channel:t}})):yield this.sendRaw({type:n.MessageType.PLAIN,data:{message:e}})}))}sendRaw(e){return o(this,void 0,void 0,(function*(){yield this.physicSend(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,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractServerSocketManager=void 0;const r=i(2318),s=i(2255),a=i(1532),d=i(9990),l=i(2665),c="x-socket-action",u="read",p="write";let h=class SocketReadCondition extends s.AbstractAccessCondition{resolveConditionValue(e){return n(this,void 0,void 0,(function*(){return e.headers["x-socket-action"]===u}))}validate(e){return n(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"disable_write",description:"Disable send message to channel",valueType:r.AccessConditionValueType.BOOLEAN}}};h=o([(0,r.Register)()],h);let f=class SocketWriteCondition extends s.AbstractAccessCondition{resolveConditionValue(e){return n(this,void 0,void 0,(function*(){return e.headers["x-socket-action"]===p}))}validate(e){return n(this,void 0,void 0,(function*(){return!!e}))}getConditionMetadata(){return{name:"disable_read",description:"Disable receive message from channel",valueType:r.AccessConditionValueType.BOOLEAN}}};f=o([(0,r.Register)()],f);t.AbstractServerSocketManager=class AbstractServerSocketManager{constructor(e,t,i,o,n){this.requireAuthentication=e,this.logger=t,this.redisClient=i,this.principalResolver=o,this.requestAuthorizer=n,this._connectionHandler=null}getUniqueChannelPrefix(){return"CHANNEL:"}getSocketInfoHashKey(){return"__SOCKET_INFO__"}getConnectionHandler(){return n(this,void 0,void 0,(function*(){if(null===this._connectionHandler){const e=(0,r.getServiceProvider)().getInjector();this._connectionHandler=e.resolveOptional(d.AbstractSocketConnectionHandler),yield e.initInstances()}return this._connectionHandler}))}formatBroadcastData(e,t){return{type:r.MessageType.PLAIN,data:{channel:e,message:t}}}getUniqueChannelName(e){return`${this.getUniqueChannelPrefix()}${e}`}getSocketIdsOfChannel(e){return n(this,void 0,void 0,(function*(){return(yield this.redisClient.smembers(this.getUniqueChannelName(e)))||[]}))}addSocketToChannel(e,t){return n(this,void 0,void 0,(function*(){const i=yield this.getById(e);return i&&(i.addChannels(t),yield Promise.all(t.map((t=>this.redisClient.sadd(this.getUniqueChannelName(t.name),e)))),yield i.saveSocketInfo()),i}))}removeSocketFromChannel(e,t,i=!0){return n(this,void 0,void 0,(function*(){if(!t.length)return;const o=yield this.getById(e);o&&(o.removeChannels(t),yield Promise.all(t.map((t=>this.redisClient.srem(this.getUniqueChannelName(t),e)))),i&&(yield o.saveSocketInfo()))}))}removeSocket(e,t=!0){return n(this,void 0,void 0,(function*(){const t=yield this.getById(e);t&&(this.logger.debug("Remove from all channels"),yield this.removeSocketFromChannel(e,t.getChannelsInfo().map((e=>e.name)),!1)),this.logger.debug("Remove from redis"),yield this.redisClient.hdel(this.getSocketInfoHashKey(),e)}))}handle(e){return n(this,void 0,void 0,(function*(){this.logger.debug("Handle socket data",e);const t=yield this.getConnectionHandler();switch(e.method){case r.SocketMethod.CONNECT:{this.logger.debug("Socket connection attempt",e);const t=new a.HttpRequest({method:r.SocketMethod.CONNECT,query:e.data.queries,pathName:""}),i=yield this.principalResolver.resolvePrincipal(t);if(!i&&this.requireAuthentication)throw r.Errors.ACCESS_DENIED("Authentication required");yield this.addSocket({id:e.socketId,authInfo:i,channels:[],createdAt:Date.now()},e.data);break}case r.SocketMethod.DISCONNECT:{this.logger.debug("Socket disconnect",e);const i=yield this.getById(e.socketId);if(i){const e=yield this.getMountedEndpointInfo();this.logger.debug("Notify channels");for(const t of i.getChannelsInfo()){const o=e.find((e=>e.endpointMetadata.url===t.name));o&&o.endpoint.controller.onChannelLeave(i)}this.logger.debug("Calling disconnection handler"),null==t||t.onSocketDisconnect(i),this.logger.debug("Removing socket"),yield this.removeSocket(i.getId(),!1)}break}case r.SocketMethod.MESSAGE:{this.logger.debug("Socket message",e);const i=e.data;let o=yield this.getById(e.socketId);if(o)switch(i.type){case r.MessageType.READY:yield o.sendRaw({type:r.MessageType.READY,data:""}),yield null==t?void 0:t.onSocketConnect(o);break;case r.MessageType.PING_PONG:yield o.sendRaw({type:r.MessageType.PING_PONG,data:i.data});break;case r.MessageType.CHANNEL_JOIN:{const e=i.data,t=[],n=[];for(const i of e){let e=!1,o=!1;const s=(yield this.getMountedEndpointInfo()).find((e=>e.endpointMetadata.url===i));if(s){try{const e=new a.HttpRequest({method:r.SocketMethod.MESSAGE,pathName:i,headers:{[c]:u}},s.endpointMetadata);yield this.requestAuthorizer.authorize(e,s),o=!0}catch(e){this.logger.debug("Error in read authorize",e)}try{const t=new a.HttpRequest({method:r.SocketMethod.MESSAGE,pathName:i,headers:{[c]:p}},s.endpointMetadata);yield this.requestAuthorizer.authorize(t,s),e=!0}catch(e){this.logger.debug("Error in write authorize",e)}(e||o)&&(this.logger.debug("Adding channel info",i,e,o),t.push({name:i,clientToServerAllowed:e,serverToClientAllowed:o}),n.push(s))}}o=yield this.addSocketToChannel(o.getId(),t),o?yield Promise.all([o.sendRaw({type:r.MessageType.CHANNEL_JOIN,data:t.map((e=>e.name))}),...n.map((e=>e.endpoint.controller.onChannelJoin(o)))]):this.logger.debug("Socket not found after addSocketToChannel")}break;case r.MessageType.CHANNEL_LEAVE:{const e=i.data,t=yield this.getMountedEndpointInfo();Promise.all(e.map((e=>()=>{const i=t.find((t=>t.endpointMetadata.url===e));if(i)return i.endpoint.controller.onChannelLeave(o)}))),yield this.removeSocketFromChannel(o.getId(),e)}break;case r.MessageType.PLAIN:{const e=i.data.channel,n=i.data.message;if(e){if(o.getChannelsInfo().find((t=>t.name===e&&t.clientToServerAllowed))){const t=(yield this.getMountedEndpointInfo()).find((t=>t.endpointMetadata.url===e));if(t){!1!==(yield t.endpoint.controller.onMessage(o,n))&&(this.logger.debug("broadcasting to channel",e,n),this.broadcastToChannel(e,n))}}}else yield null==t?void 0:t.onMessage(o,n)}break;default:this.logger.debug("Invalid message format",i)}else this.logger.debug("Socket not found",e.socketId);break}default:return}}))}getMountedEndpointInfo(){return n(this,void 0,void 0,(function*(){if(!this.mountedEndpointInfo){const e=(0,r.getServiceProvider)().getInjector(),t=e.resolveMultiple(l.AbstractSocketController);yield e.initInstances(),this.mountedEndpointInfo=t.map((e=>{const t=(0,r.getObjectMetadata)(e.constructor);return{endpoint:{httpMethod:r.SocketMethod.MESSAGE,mount:e.getChannelName(),controller:e,handlerFunctionName:e.onMessage.name},endpointMetadata:{httpMethod:r.SocketMethod.MESSAGE,description:"Send / Receive message to / from channel",permissionGroup:t.permissionGroup,dataType:r.DataType.OBJECT,url:e.getChannelName(),name:e.getChannelName(),accessConditions:[h,f]}}}))}return this.mountedEndpointInfo}))}}},9990:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketConnectionHandler=void 0;t.AbstractSocketConnectionHandler=class AbstractSocketConnectionHandler{}},2665:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractSocketController=void 0;const n=i(8985);class AbstractSocketController extends n.AbstractController{onChannelJoin(e){return o(this,void 0,void 0,(function*(){}))}onChannelLeave(e){return o(this,void 0,void 0,(function*(){}))}onMessage(e,t){return o(this,void 0,void 0,(function*(){}))}}t.AbstractSocketController=AbstractSocketController},7152:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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=i(2318),d=s(i(9336)),l=s(i(1495)),c=i(767),u=i(5530),p=i(6862),h=i(5709),f=i(4638);class ApiGatewaySocket extends p.AbstractServerSocket{constructor(e,t,i,o,n){super(t),this.socketManager=e,this.socketInfo=t,this.apiGateway=i,this.socketNamespace=o,this.redisClient=n}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.redisClient.hset(this.socketNamespace,this.socketInfo.id,JSON.stringify(this.socketInfo))}))}physicSend(e){return r(this,void 0,void 0,(function*(){yield this.socketManager.physicSend(this.getId(),e)}))}disconnect(e){return r(this,void 0,void 0,(function*(){e&&(yield this.physicSend(e)),yield this.socketManager.removeSocket(this.getId())}))}serialize(){return JSON.stringify(this.socketInfo)}}let v=class AwsSocketManager extends u.AbstractServerSocketManager{constructor(e,t,i,o,n,r,s,a){super(e,a,o,r,s),this.authenticationRequired=e,this.region=t,this.socketDomainUrl=i,this.redis=o,this.httpRequestHandler=n,this.principalResolver=r,this.requestAuthorizer=s,this.logger=a,this.apiGatewayManagement=new d.default.ApiGatewayManagementApi({region:t,apiVersion:"2018-11-29",endpoint:i})}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)}))}physicSend(e,t){return r(this,void 0,void 0,(function*(){try{this.logger.debug(`Socket ${e} sending`,t),yield this.apiGatewayManagement.postToConnection({ConnectionId:e,Data:JSON.stringify(t)}).promise()}catch(t){throw this.logger.debug(`Socket ${e} post error`,t),410===t.statusCode&&(this.logger.debug(`Disconnect & remove stale socket ${e}`),yield this.removeSocket(e,!1),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 i=yield this.getSocketIdsOfChannel(e);if(i.length){const o=this.formatBroadcastData(e,t);i.map((e=>this.physicSend(e,o).catch((t=>this.logger.error(`Cannot send to socket ${e}`,t)))))}}))}addSocket(e,t){return r(this,void 0,void 0,(function*(){const t=new ApiGatewaySocket(this,e,this.apiGatewayManagement,this.getSocketInfoHashKey(),this.redisClient);return yield t.saveSocketInfo(),t}))}removeSocket(e,t=!0){const i=Object.create(null,{removeSocket:{get:()=>super.removeSocket}});return r(this,void 0,void 0,(function*(){this.logger.debug(`Aws socket manager remove socket: ${e}, ${t}`),yield i.removeSocket.call(this,e,t),this.logger.debug("Super remove ok"),t&&this.apiGatewayManagement.deleteConnection({ConnectionId:e}).promise().catch((e=>this.logger.error("Cannot physic remove aws socket",e)))}))}getSocketBySerialized(e){return new ApiGatewaySocket(this,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)}))}};v=o([(0,a.Initable)(),(0,a.LogContext)(),n("design:paramtypes",[Boolean,String,String,l.default,c.AbstractHttpRequestHandler,f.AbstractPrincipalResolver,h.AbstractRequestAuthorizer,a.AbstractLogger])],v),t.AwsSocketManager=v},8577:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},2841:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.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=i(2318),d=s(i(5352)),l=s(i(9215)),c=s(i(9103)),u=s(i(1495)),p=i(5530),h=i(6862),f=i(5709),v=i(4638);var y;!function(e){e.SEND="SEND",e.CLOSE="CLOSE",e.SAVE="SAVE"}(y||(y={}));class RedisSocket extends h.AbstractServerSocket{constructor(e,t,i){super(i),this.socketChannelName=e,this.redisClient=t,this.socketInfo=i}physicSend(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:y.SEND,data:e}))}))}disconnect(e){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:y.CLOSE,data:e}))}))}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.redisClient.publish(this.socketChannelName,JSON.stringify({type:y.SAVE,data:this.socketInfo}))}))}}class ExpressSocket extends h.AbstractServerSocket{constructor(e,t,i,o){super(i),this.socketManager=e,this.socket=t,this.socketInfo=i,this.infoSaver=o}saveSocketInfo(){return r(this,void 0,void 0,(function*(){yield this.infoSaver(this.socketInfo)}))}physicSend(e){return r(this,void 0,void 0,(function*(){this.socket.send(JSON.stringify(e))}))}disconnect(e){return r(this,void 0,void 0,(function*(){this.socket.close(1e3,e&&JSON.stringify(e)),yield this.socketManager.removeSocket(this.getId())}))}}let g=class LocalSocketManager extends p.AbstractServerSocketManager{constructor(e,t,i,o,n,r,s){super(e,n,o,r,s),this.authenticationRequired=e,this.subClient=t,this.channelSubClient=i,this.sendClient=o,this.logger=n,this.principalResolver=r,this.requestAuthorizer=s,this.allSockets=[],this.subscribedChannels=[]}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.logger.info("LocalSocketManager exit")}channelMessageListenner(e,t){this.logger.debug("Receiving message from channel",t,e);const i=JSON.parse(e);i.type===a.MessageType.PLAIN&&this.allSockets.forEach((e=>{e.send(i.data.message,i.data.channel)}))}socketMessageListener(e,t){this.logger.debug("Receiving message from remote socket channel",t,e);const i=t.substring(this.getSocketChannelKeyPrefix().length),o=this.allSockets.find((e=>e.getId()===i));if(o){const t=JSON.parse(e);switch(t.type){case y.SEND:o.physicSend(t.data);break;case y.SAVE:o.socketInfo.channels=t.data,o.saveSocketInfo();break;case y.CLOSE:o.disconnect(t.data);break;default:this.logger.debug("Invalid remote command",t)}}}getUniqueDataChannelName(e){return`CHANNEL_DATA:${e}`}getSocketChannelKeyPrefix(){return"SOCKET_CHANNEL:"}getSocketChannelKey(e){return`${this.getSocketChannelKeyPrefix()}${e}`}broadcastToChannel(e,t){return r(this,void 0,void 0,(function*(){const i=this.formatBroadcastData(e,t);yield this.redisClient.publish(this.getUniqueDataChannelName(e),JSON.stringify(i))}))}addSocketToChannel(e,t){const i=Object.create(null,{addSocketToChannel:{get:()=>super.addSocketToChannel}});return r(this,void 0,void 0,(function*(){const o=yield i.addSocketToChannel.call(this,e,t),n=t.map((e=>e.name)).filter((e=>!this.subscribedChannels.includes(e)));return n.length&&(yield Promise.all(n.map((e=>this.channelSubClient.subscribe(this.getUniqueDataChannelName(e))))),this.subscribedChannels.push(...n)),o}))}removeSocketFromChannel(e,t,i=!0){const o=Object.create(null,{removeSocketFromChannel:{get:()=>super.removeSocketFromChannel}});return r(this,void 0,void 0,(function*(){yield o.removeSocketFromChannel.call(this,e,t,i),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 i=new ExpressSocket(this,t,e,(e=>r(this,void 0,void 0,(function*(){yield this.redisClient.hset(this.getSocketInfoHashKey(),e.id,JSON.stringify(e))})))),o=this.getSocketChannelKey(e.id);return yield this.subClient.subscribe(o),this.allSockets.push(i),i}))}removeSocket(e,t=!0){const i=Object.create(null,{removeSocket:{get:()=>super.removeSocket}});return r(this,void 0,void 0,(function*(){yield i.removeSocket.call(this,e,t);const o=this.getSocketChannelKey(e);yield this.subClient.unsubscribe(o),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 i=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)}))));i&&(t=new RedisSocket(this.getSocketChannelKey(e),this.sendClient,i))}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 i=t.headers["sec-websocket-key"];let o=!1,n=[];const r=(0,l.default)({url:t.url}),s=c.default.parse(decodeURIComponent(r.search||""));this.handle({method:a.SocketMethod.CONNECT,socketId:i,data:{queries:s,socket:e}}).then((()=>{o=!0;for(const e of n)this.handle(e).catch((e=>{this.logger.error(e)}))})).catch((t=>{n=[],e.close(1e3,`${t.name}:${t.message}`)})),e.onmessage=e=>{const t={method:a.SocketMethod.MESSAGE,socketId:i,data:e.data&&JSON.parse(e.data)};o?this.handle(t).catch((e=>{this.logger.error(e)})):n.push(t)},e.onclose=()=>{this.handle({method:a.SocketMethod.DISCONNECT,socketId:i}).catch((e=>{this.logger.error(e)}))}}))}};g=o([(0,a.Initable)(),(0,a.LogContext)(),n("design:paramtypes",[Boolean,u.default,u.default,u.default,a.AbstractLogger,v.AbstractPrincipalResolver,f.AbstractRequestAuthorizer])],g),t.LocalSocketManager=g},5537:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=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,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.ClaireServer=void 0;const s=i(2318),a=i(137),d=i(767),l=i(5530),c=i(9202);let u=class ClaireServer extends s.ClaireApp{constructor(e,t,i){super(),this.logger=e,this.httpRequestHandler=t,this.socketManager=i,this.booted=!1}init(){return r(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,c.getEndpointId)(t.endpoint)}`);(0,s.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(a.ExitCode.SIGTERM_INTERUPTION)))),process.on("SIGINT",(()=>(this.logger.warn("SIGINT interrupt signal"),this.stop(a.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)}};u=o([(0,s.LogContext)(),n("design:paramtypes",[s.AbstractLogger,d.AbstractHttpRequestHandler,l.AbstractServerSocketManager])],u),t.ClaireServer=u},226:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))},n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ExpressWrapper=void 0;const r=i(2318),s=n(i(6860)),a=n(i(3685)),d=n(i(9710)),l=n(i(6674)),c=n(i(3582)),u=i(5530),p=i(767);t.ExpressWrapper=class ExpressWrapper{constructor(e,t){this.server=e,this.config=t,this.injector=(0,r.getServiceProvider)().getInjector(),this.socketManager=this.injector.resolveOptional(u.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(p.AbstractHttpRequestHandler)}close(){var e;null===(e=this.httpServer)||void 0===e||e.close(),this.server.exit()}listen(e){var t,i,n,u;return o(this,void 0,void 0,(function*(){yield this.server.init(),yield this.injector.initInstances();const p=(0,s.default)(),h=a.default.createServer(p);null===(t=this.socketManager)||void 0===t||t.configure(h),(null===(i=this.httpRequestHandler)||void 0===i?void 0:i.corsConfig)&&p.use((0,c.default)({allowedHeaders:this.httpRequestHandler.corsConfig.headers,credentials:this.httpRequestHandler.corsConfig.credentials,origin:this.httpRequestHandler.corsConfig.origins,methods:this.httpRequestHandler.corsConfig.methods}));const f=1024*((null===(u=null===(n=this.config)||void 0===n?void 0:n.requestSetting)||void 0===u?void 0:u.maxBodySizeKB)||10240);return p.use((0,d.default)()),p.use(s.default.json({limit:f})),p.use(s.default.urlencoded({extended:!1,limit:f})),p.use((0,l.default)()),p.use(((e,t,i)=>{e.files&&(e.body||(e.body={}),Object.keys(e.files).forEach((t=>{e.body[t]=e.files[t]}))),i()})),p.use(s.default.raw({limit:f,type:e=>!["application/json","application/x-www-form-urlencoded"].find((t=>{var i;return null===(i=e.headers["content-type"])||void 0===i?void 0:i.includes(t)}))})),p.all("*",((e,t)=>{(()=>o(this,void 0,void 0,(function*(){if(!!e.headers["x-amzn-apigateway-api-id"]){if(!this.socketManager)throw r.Errors.SYSTEM_ERROR("Socket manager not found");const i={socketId:e.body.connectionId,data:e.body.data,method:e.body.type.toLowerCase()};if(i.method===r.SocketMethod.CONNECT){const t=e.body.data.querystring,o=t.substring(1,t.length-1).split(",").map((e=>e.trim().split("="))).reduce(((e,t)=>Object.assign(e,{[t[0]]:t[1]})),{});i.data={queries:o}}yield this.socketManager.handle(i),t.status(200).send()}else{if(!this.httpRequestHandler)throw r.Errors.SYSTEM_ERROR("Http request handler not found");const i={clientIP:e.ip||e.headers["x-forwarded-for"],fullPath:e.url,method:e.method.toLowerCase(),headers:e.headers,body:e.body,cookies:e.cookies},o=yield this.httpRequestHandler.handle(i);o.headers&&Object.keys(o.headers).forEach((e=>{t.set(e,o.headers[e])})),o.cookies&&Object.keys(o.cookies).forEach((e=>{t.cookie(e,o.cookies[e].value,o.cookies[e].options||{})})),t.status(o.code||200).send(o.value)}})))().catch((e=>{t.status(e.code||500).json({name:e.name,message:e.message,code:e.code||500})}))})),new Promise(((t,i)=>{this.httpServer=h.listen(e,t).on("error",i)}))}))}}},8836:function(e,t,i){var o=this&&this.__awaiter||function(e,t,i,o){return new(i||(i=Promise))((function(n,r){function fulfilled(e){try{step(o.next(e))}catch(e){r(e)}}function rejected(e){try{step(o.throw(e))}catch(e){r(e)}}function step(e){e.done?n(e.value):function adopt(e){return e instanceof i?e:new i((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((o=o.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.LambdaWrapper=void 0;const n=i(2318),r=i(767),s=i(3376),a=i(2363),d=i(5530),toApiGatewayFormat=e=>({statusCode:e.code||200,body:e.value&&JSON.stringify(e.value),headers:e.headers,cookies:Object.keys(e.cookies||{}).map((t=>{var i,o,n,r,s,a,d,l,c,u,p;const h=e.cookies[t];let f=`${t}=${h.value}`;return(null===(i=h.options)||void 0===i?void 0:i.maxAge)&&(f+=`; MaxAge=${h.options.maxAge}`),(null===(o=h.options)||void 0===o?void 0:o.expires)&&(f+=`; Expires=${h.options.expires.toUTCString()}`),(null===(n=h.options)||void 0===n?void 0:n.httpOnly)&&(f+="; HttpOnly"),(null===(r=h.options)||void 0===r?void 0:r.path)&&(f+=`; Path=${null===(s=h.options)||void 0===s?void 0:s.path}`),(null===(a=h.options)||void 0===a?void 0:a.domain)&&(f+=`; Domain=${null===(d=h.options)||void 0===d?void 0:d.domain}`),(null===(l=h.options)||void 0===l?void 0:l.secure)&&(f+="; Secure"),(null===(c=h.options)||void 0===c?void 0:c.sameSite)&&("boolean"==typeof(null===(u=h.options)||void 0===u?void 0:u.sameSite)?f+="; SameSite":f+=`; SameSite=${null===(p=h.options)||void 0===p?void 0:p.sameSite}`),f}))});t.LambdaWrapper=class LambdaWrapper{constructor(e,t,i){this.serverFactory=e,this.requestMapper=t,this.config=i,this.injector=(0,n.getServiceProvider)().getInjector(),this.handler=this.handler.bind(this),this.socketManager=this.injector.resolveOptional(d.AbstractServerSocketManager),this.httpRequestHandler=this.injector.resolveOptional(r.AbstractHttpRequestHandler),this.jobScheduler=this.injector.resolveOptional(s.AwsJobScheduler)}bootServer(){var e;return o(this,void 0,void 0,(function*(){this._server||(this._server=yield this.serverFactory(),yield this.injector.initInstances(),null===(e=this.socketManager)||void 0===e||e.configure(),yield this._server.init())}))}handler(e){var t,i,r,s;return o(this,void 0,void 0,(function*(){yield this.bootServer();const o=this.requestMapper(e);if(!o)throw n.Errors.SYSTEM_ERROR("Cannot resolve event");const d=((e,t)=>{const i={};return(null==t?void 0:t.credentials)&&(i["Access-Control-Allow-Credentials"]="true"),(null==t?void 0:t.headers)&&(i["Access-Control-Allow-Headers"]="string"==typeof t.headers?t.headers:t.headers.join(", ")),(null==t?void 0:t.methods)&&(i["Access-Control-Allow-Methods"]="string"==typeof t.methods?t.methods:t.methods.join(", ")),(null==t?void 0:t.origins)&&(i["Access-Control-Allow-Origin"]="string"==typeof t.origins?t.origins:t.origins.find((t=>e.match(t)))?e:""),i})((null===(t=o.headers)||void 0===t?void 0:t.origin)||"",null===(i=this.httpRequestHandler)||void 0===i?void 0:i.corsConfig);if(o.method===n.HttpMethod.OPTIONS)return toApiGatewayFormat({code:200,headers:d,cookies:{}});if(o.method===a.INTERVAL_REQUEST_METHOD)return yield null===(r=this.jobScheduler)||void 0===r?void 0:r.handleInterval(o.body),toApiGatewayFormat({code:200,headers:d,cookies:{}});if(o.method===a.CRON_REQUEST_METHOD)return yield null===(s=this.jobScheduler)||void 0===s?void 0:s.handleCron(o.body),toApiGatewayFormat({code:200,headers:d,cookies:{}});try{if(Object.values(n.HttpMethod).includes(o.method)){if(!this.httpRequestHandler)throw n.Errors.SYSTEM_ERROR("Http request handler not found");const e={clientIP:o.clientIP,fullPath:o.rawPath,method:o.method,headers:o.headers,cookies:o.cookies,body:o.body},t=yield this.httpRequestHandler.handle(e);return toApiGatewayFormat(Object.assign(Object.assign({},t),{headers:Object.assign(Object.assign({},d),t.headers)}))}if(!Object.values(n.SocketMethod).includes(o.method))throw n.Errors.HTTP_REQUEST_ERROR("Not allow request method: "+o.method);{if(!this.socketManager)throw n.Errors.SYSTEM_ERROR("Socket manager not found");const e={socketId:o.rawPath,method:o.method,data:o.body};yield this.socketManager.handle(e)}return toApiGatewayFormat({code:200,headers:d,cookies:{}})}catch(e){return toApiGatewayFormat({code:e.code||500,value:{name:e.name,message:e.message,code:e.code||500},headers:d,cookies:{}})}}))}}},9627:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},889:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.lambdaRequestMapper=void 0;const o=i(2318),n=i(2363),parseCookie=e=>{let t={};for(const i of e){const e=i.split("=");e[0]&&e[1]&&(t[e[0]]=e[1])}return t};t.lambdaRequestMapper=e=>{if(e.requestContext.eventType){const t=e.requestContext.eventType.toLowerCase(),i=e.body&&JSON.parse(e.body);return{method:t,rawPath:e.requestContext.connectionId,body:t===o.SocketMethod.CONNECT?{queries:e.queryStringParameters}:i}}return e.requestContext.intervalScheduler?{method:n.INTERVAL_REQUEST_METHOD,rawPath:"",body:e.requestContext.intervalScheduler.time}:e.requestContext.cronScheduler?{method:n.CRON_REQUEST_METHOD,rawPath:"",body:e.requestContext.cronScheduler.data}:{clientIP:e.requestContext.http.sourceIp,method:e.requestContext.http.method.toLowerCase(),rawPath:`${e.rawPath}?${e.rawQueryString}`,body:e.body&&JSON.parse(e.body),headers:e.headers,cookies:parseCookie(e.cookies||[])}}},5481:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s};Object.defineProperty(t,"__esModule",{value:!0}),t.LocaleEntry=void 0;const n=i(2318);let r=class LocaleEntry extends n.AbstractModel{};r=o([(0,n.Model)()],r),t.LocaleEntry=r},2552:function(e,t,i){var o=this&&this.__decorate||function(e,t,i,o){var n,r=arguments.length,s=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,i):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,o);else for(var a=e.length-1;a>=0;a--)(n=e[a])&&(s=(r<3?n(s):r>3?n(t,i,s):n(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},n=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};Object.defineProperty(t,"__esModule",{value:!0}),t.LocaleTranslation=void 0;const r=i(2318),s=i(5481);let a=class LocaleTranslation extends r.AbstractModel{};o([(0,r.Column)(Object.assign({description:"Id of the locale",isRequired:!0},(0,r.FK)({model:s.LocaleEntry,cascade:"delete"}))),n("design:type",String)],a.prototype,"entryId",void 0),o([(0,r.Column)({description:"Code of locale",isRequired:!0,textLength:3}),n("design:type",String)],a.prototype,"localeCode",void 0),o([(0,r.Column)({description:"Translation of locale",isRequired:!0}),n("design:type",String)],a.prototype,"translation",void 0),a=o([(0,r.Model)(),(0,r.Index)([["entryId",1],["localeCode",1]],{unique:!0})],a),t.LocaleTranslation=a},10:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LocaleOf=void 0;const o=i(2318),n=i(5481);t.LocaleOf=e=>(t,i)=>{const r=(0,o.initFieldMetadata)(t,i);r.multiLocaleColumn=e,r.fk=(0,o.FK)({model:n.LocaleEntry,cascade:"nullify"}).fk,r.dataType=o.DataType.NUMBER;(0,o.initFieldMetadata)(t,e).isMultiLocale=!0}},2318:e=>{e.exports=require("@clairejs/core")},7756:e=>{e.exports=require("@clairejs/orm")},9336:e=>{e.exports=require("aws-sdk")},2167:e=>{e.exports=require("axios")},9710:e=>{e.exports=require("cookie-parser")},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")},7344:e=>{e.exports=require("node-schedule")},9215:e=>{e.exports=require("parseurl")},99:e=>{e.exports=require("path-to-regexp")},9103:e=>{e.exports=require("query-string")},7325:e=>{e.exports=require("randomstring")},9896:e=>{e.exports=require("redlock")},5352:e=>{e.exports=require("ws")},7147:e=>{e.exports=require("fs")},3685:e=>{e.exports=require("http")},1017:e=>{e.exports=require("path")},9512:e=>{e.exports=require("timers")}},t={};var i=function __webpack_require__(i){var o=t[i];if(void 0!==o)return o.exports;var n=t[i]={exports:{}};return e[i].call(n.exports,n,n.exports,__webpack_require__),n.exports}(341);return i})()));
|