@resolveio/server-lib 20.5.0 → 20.5.3

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.
Files changed (113) hide show
  1. package/collections/app-status.collection.js +1 -1
  2. package/collections/app-status.collection.js.map +1 -1
  3. package/collections/counter.collection.js +1 -1
  4. package/collections/counter.collection.js.map +1 -1
  5. package/collections/cron-job-history.collection.js +1 -1
  6. package/collections/cron-job-history.collection.js.map +1 -1
  7. package/collections/cron-job.collection.js +1 -1
  8. package/collections/cron-job.collection.js.map +1 -1
  9. package/collections/email-history.collection.js +1 -1
  10. package/collections/email-history.collection.js.map +1 -1
  11. package/collections/email-verified.collection.js +1 -1
  12. package/collections/email-verified.collection.js.map +1 -1
  13. package/collections/file.collection.js +1 -1
  14. package/collections/file.collection.js.map +1 -1
  15. package/collections/flag-update.collection.js +1 -1
  16. package/collections/flag-update.collection.js.map +1 -1
  17. package/collections/flag.collection.js +1 -1
  18. package/collections/flag.collection.js.map +1 -1
  19. package/collections/log-method-latency.collection.js +1 -1
  20. package/collections/log-method-latency.collection.js.map +1 -1
  21. package/collections/log-subscription.collection.js +1 -1
  22. package/collections/log-subscription.collection.js.map +1 -1
  23. package/collections/log.collection.js +1 -1
  24. package/collections/log.collection.js.map +1 -1
  25. package/collections/logged-in-users.collection.js +1 -1
  26. package/collections/logged-in-users.collection.js.map +1 -1
  27. package/collections/method-response.collection.js +1 -1
  28. package/collections/method-response.collection.js.map +1 -1
  29. package/collections/monitor-cpu.collection.js +1 -1
  30. package/collections/monitor-cpu.collection.js.map +1 -1
  31. package/collections/monitor-memory.collection.js +1 -1
  32. package/collections/monitor-memory.collection.js.map +1 -1
  33. package/collections/monitor-mongo.collection.js +1 -1
  34. package/collections/monitor-mongo.collection.js.map +1 -1
  35. package/collections/notification.collection.js +1 -1
  36. package/collections/notification.collection.js.map +1 -1
  37. package/collections/report-builder-dashboard-builder.collection.js +1 -1
  38. package/collections/report-builder-dashboard-builder.collection.js.map +1 -1
  39. package/collections/report-builder-library.collection.js +1 -1
  40. package/collections/report-builder-library.collection.js.map +1 -1
  41. package/collections/report-builder-report.collection.js +1 -1
  42. package/collections/report-builder-report.collection.js.map +1 -1
  43. package/collections/user-group.collection.js +1 -1
  44. package/collections/user-group.collection.js.map +1 -1
  45. package/collections/user-guide.collection.js +1 -1
  46. package/collections/user-guide.collection.js.map +1 -1
  47. package/collections/user.collection.js +1 -1
  48. package/collections/user.collection.js.map +1 -1
  49. package/collections/worker-task-request.collection.js +1 -1
  50. package/collections/worker-task-request.collection.js.map +1 -1
  51. package/collections/worker-task-response.collection.js +1 -1
  52. package/collections/worker-task-response.collection.js.map +1 -1
  53. package/fixtures/cron-jobs.js +1 -1
  54. package/fixtures/cron-jobs.js.map +1 -1
  55. package/fixtures/init.js +1 -1
  56. package/fixtures/init.js.map +1 -1
  57. package/http/auth.d.ts +1 -2
  58. package/http/auth.js +1 -1
  59. package/http/auth.js.map +1 -1
  60. package/http/home.d.ts +1 -2
  61. package/http/home.js +1 -1
  62. package/http/home.js.map +1 -1
  63. package/index.d.ts +0 -30
  64. package/index.js +1 -1
  65. package/index.js.map +1 -1
  66. package/managers/cron.manager.js +1 -1
  67. package/managers/cron.manager.js.map +1 -1
  68. package/managers/local-log.manager.js +1 -1
  69. package/managers/local-log.manager.js.map +1 -1
  70. package/managers/method.manager.js +1 -1
  71. package/managers/method.manager.js.map +1 -1
  72. package/managers/mongo.manager.d.ts +1 -2
  73. package/managers/mongo.manager.js +1 -1
  74. package/managers/mongo.manager.js.map +1 -1
  75. package/managers/monitor.manager.d.ts +0 -1
  76. package/managers/monitor.manager.js +1 -1
  77. package/managers/monitor.manager.js.map +1 -1
  78. package/managers/subscription.manager.js +1 -1
  79. package/managers/subscription.manager.js.map +1 -1
  80. package/managers/websocket.manager.d.ts +1 -2
  81. package/managers/websocket.manager.js.map +1 -1
  82. package/methods/accounts.js +1 -1
  83. package/methods/accounts.js.map +1 -1
  84. package/methods/aws.js +1 -1
  85. package/methods/aws.js.map +1 -1
  86. package/methods/collections.js +1 -1
  87. package/methods/collections.js.map +1 -1
  88. package/methods/counters.js +1 -1
  89. package/methods/counters.js.map +1 -1
  90. package/methods/logs.js +1 -1
  91. package/methods/logs.js.map +1 -1
  92. package/methods/monitor.js +1 -1
  93. package/methods/monitor.js.map +1 -1
  94. package/methods/report-builder.js +1 -1
  95. package/methods/report-builder.js.map +1 -1
  96. package/package.json +1 -1
  97. package/public_api.d.ts +1 -0
  98. package/public_api.js +1 -1
  99. package/public_api.js.map +1 -1
  100. package/resolveio-server-app.d.ts +31 -0
  101. package/resolveio-server-app.js +2 -0
  102. package/resolveio-server-app.js.map +1 -0
  103. package/server-app.d.ts +2 -1
  104. package/server-app.js +1 -1
  105. package/server-app.js.map +1 -1
  106. package/util/common.d.ts +1 -0
  107. package/util/common.js +1 -1
  108. package/util/common.js.map +1 -1
  109. package/util/schema-report-builder.js +1 -1
  110. package/util/schema-report-builder.js.map +1 -1
  111. package/client-server-app.d.ts +0 -1
  112. package/client-server-app.js +0 -2
  113. package/client-server-app.js.map +0 -1
package/server-app.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var __awaiter=this&&this.__awaiter||function(e,n,o,s){return new(o=o||Promise)(function(t,r){function fulfilled(e){try{step(s.next(e))}catch(e){r(e)}}function rejected(e){try{step(s.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof o?r:new o(function(e){e(r)})).then(fulfilled,rejected)}step((s=s.apply(e,n||[])).next())})},__generator=this&&this.__generator||function(n,o){var s,i,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},c={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function verb(t){return function(e){var r=[t,e];if(s)throw new TypeError("Generator is already executing.");for(;l=c&&r[c=0]?0:l;)try{if(s=1,i&&(a=2&r[0]?i.return:r[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,r[1])).done)return a;switch(i=0,(r=a?[2&r[0],a.value]:r)[0]){case 0:case 1:a=r;break;case 4:return l.label++,{value:r[1],done:!1};case 5:l.label++,i=r[1],r=[0];continue;case 7:r=l.ops.pop(),l.trys.pop();continue;default:if(!(a=0<(a=l.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){l=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))l.label=r[1];else if(6===r[0]&&l.label<a[1])l.label=a[1],a=r;else{if(!(a&&l.label<a[2])){a[2]&&l.ops.pop(),l.trys.pop();continue}l.label=a[2],l.ops.push(r)}}r=o.call(n,l)}catch(e){r=[6,e],i=0}finally{s=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],n=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var n,o,s=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(n=s.next()).done;)i.push(n.value)}catch(e){o={error:e}}finally{try{n&&!n.done&&(t=s.return)&&t.call(s)}finally{if(o)throw o.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var n,o=0,s=r.length;o<s;o++)!n&&o in r||((n=n||Array.prototype.slice.call(r,0,o))[o]=r[o]);return e.concat(n||Array.prototype.slice.call(r))},http_1=(Object.defineProperty(exports,"__esModule",{value:!0}),require("http")),express=require("express"),bodyParser=require("body-parser"),xmlParser=require("express-xml-bodyparser"),WebSocket=require("ws"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),common_1=require("./util/common"),mongo_manager_1=require("./managers/mongo.manager"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),subscription_manager_1=require("./managers/subscription.manager"),monitor_manager_1=require("./managers/monitor.manager"),log_collection_1=require("./collections/log.collection"),log_method_latency_collection_1=require("./collections/log-method-latency.collection"),user_collection_1=require("./collections/user.collection"),home_1=require("./http/home"),auth_1=require("./http/auth"),health_1=require("./http/health"),index_1=require("./index"),mongodb_1=require("mongodb"),worker_task_request_collection_1=require("./collections/worker-task-request.collection"),worker_task_response_collection_1=require("./collections/worker-task-response.collection"),websocket_manager_1=require("./managers/websocket.manager"),ResolveIOMainServer=function(){function ResolveIOMainServer(){var e=this;this._offlineUpdates=[],this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._workerTasks=[],this._safeShutdown=!1,this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager,this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction,this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){e._subscriptionManager&&e._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Recv Hits",e._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",e._debugMsgQueue)),e._debugMsgQueue=0,e._debugMsgRecv=0},6e4),process.on("unhandledRejection",function(n,o){return __awaiter(e,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return n&&"MongoError"===n.name&&48===n.code?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[n,o]),r=moment().diff(this._serverStartTime,"seconds"),n&&("MongoNetworkTimeoutError"===n.name||n instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+index_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify({name:n.name,message:n.message,stack:n.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,10];case 3:return n&&"MongoError"===n.name&&"not master"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+index_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,10];case 6:return n&&"MongoError"===n.name&&"not master and slaveOk=false"===n.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+index_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:n&&"StatusError"!==n.name&&""!==n.message&&60<r&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+index_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([n.name,n.message,n.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(e,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(t,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+index_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t.name,t.message,t.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGTERM",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGQUIT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance"),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=new cron_manager_1.CronManager,this.startWorkerInstance()):(console.log("Running as a Server instance"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,index_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,index_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager,this.listen())}return ResolveIOMainServer.prototype.startServerInstance=function(){this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.PORT_HTTP||index_1.ResolveIOServer.getServerConfig().PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||index_1.ResolveIOServer.getServerConfig().PORT_WSS||8081,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,r,t){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST"),r.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),r.setHeader("Access-Control-Allow-Credentials","false"),t()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,index_1.ResolveIOServer.getServerConfig()),(0,health_1.setupHealthRoutes)(this._app,index_1.ResolveIOServer.getServerConfig()),"ResolveIO"!==index_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,index_1.ResolveIOServer.getServerConfig()),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.startWorkerInstance=function(){return __awaiter(this,void 0,void 0,function(){var r,t,n,o,s,i,a,l=this;return __generator(this,function(e){switch(e.label){case 0:return console.log("Worker instance started, watching worker-task-reqs..."),(r=worker_task_request_collection_1.WorkerTaskRequests.watchCollection([{$match:{"fullDocument.status":"pending"}}],{fullDocument:"updateLookup"})).on("change",function(o){return __awaiter(l,void 0,void 0,function(){var r,t,n=this;return __generator(this,function(e){return"insert"===o.operationType?(r=o.fullDocument)&&setTimeout(function(){n.processTask(r)},25*this._workerTasks.length):"update"===o.operationType&&(t=o.fullDocument)&&"pending"===t.status&&setTimeout(function(){n.processTask(t)},25*this._workerTasks.length),[2]})})}),r.on("error",function(e){console.error("Error in change stream worker task requests:",e),r&&r.close()}),r.on("close",function(){console.log("Change stream worker task requests closed. Restarting..."),setTimeout(function(){return l.startWorkerInstance()},5e3)}),[4,worker_task_request_collection_1.WorkerTaskRequests.find({status:"pending"},{sort:{createdAt:1}})];case 1:t=e.sent();try{for(n=__values(t),o=n.next();!o.done;o=n.next())s=o.value,this.processTask(s)}catch(e){i={error:e}}finally{try{o&&!o.done&&(a=n.return)&&a.call(n)}finally{if(i)throw i.error}}return[2]}})})},ResolveIOMainServer.prototype.processTask=function(o){return __awaiter(this,void 0,void 0,function(){var r=this;return __generator(this,function(e){return this._workerTasks.includes(o._id)||worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:o._id,status:"pending"},{$set:{status:"processing"}}).then(function(n){return __awaiter(r,void 0,void 0,function(){var r,t;return __generator(this,function(e){switch(e.label){case 0:if(!n)return[3,5];this._workerTasks.push(o._id),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(t=this._methodManager.callMethodInternal).call.apply(t,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:o.id_user,user:o.user,id_ws:o.id_ws}),o.method],__read(o.params),!1))];case 2:return t=e.sent(),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:o._id,has_error:!1,data:t,id_user:o.id_user,user:o.user,id_ws:o.id_ws}),[3,4];case 3:return r=e.sent(),console.error("Worker failed to process task:",o._id,r),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:o._id,has_error:!0,data:r.message,id_user:o.id_user,user:o.user,id_ws:o.id_ws}),[3,4];case 4:this._workerTasks.includes(o._id)&&this._workerTasks.splice(this._workerTasks.indexOf(o._id),1),worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:o._id},{$set:{status:"complete"}}),e.label=5;case 5:return[2]}})})},function(){}),[2]})})},ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length?(this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){e._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):index_1.ResolveIOServer.getMongoConnection()?index_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)}):process.exit(0)},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWSList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_socket)}),r},ResolveIOMainServer.prototype.getWSUserList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_user)}),r},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.getWebSocketManager=function(){return this._websocketManager},ResolveIOMainServer.prototype.createServer=function(){var e=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({port:this._portWSS,verifyClient:this.publicProgram?null:function(s,i){return __awaiter(e,void 0,void 0,function(){var r,o=this;return __generator(this,function(e){return this._rebootFlag?i(!1,409,"Unable To Process"):("DEBUG"===this.LOGGER&&console.log("Verify Client",s,i),r=s.req.headers["sec-websocket-protocol"].split(/,/),(s.origin===index_1.ResolveIOServer.getServerConfig().ROOT_URL||s.origin===index_1.ResolveIOServer.getServerConfig().SEC_ROOT_URL||s.origin===index_1.ResolveIOServer.getServerConfig().RESOLVEIO_URL||s.origin===index_1.ResolveIOServer.getServerConfig().RESOLVEIO_SECONDARY_URL)&&(r=r[0])?jwt.verify(r,index_1.ResolveIOServer.getServerConfig().JWT_SECRET,function(t,n){return __awaiter(o,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return t?(i(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:s.req.id_user=n.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(n.id_user)];case 3:return(r=e.sent())?(s.req.user=r.fullname,s.req.user_readonly=r.readonly||!1,s.req.doc_user=r,i(!0)):i(!1),[3,5];case 4:return e.sent(),i(!1),[3,5];case 5:return[2]}})})}):i(!1,401,"Unauthorized")),[2]})})}})},ResolveIOMainServer.prototype.listen=function(){var t=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",t._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",t._portWSS)}),this._serverWSS.on("connection",function(c,e){t.publicProgram||(c.id_user=e.id_user,c.user=e.user,c.user_readonly=e.user_readonly,c.doc_user=e.doc_user,"Admin"!==c.user&&"ResolveIO"!==index_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&t.getMethodManager().callMethodInternal.call(t.getMethodManager(),"supportCreateBillingUser",{id_user:c.id_user,user:c.user,date:new Date,client:index_1.ResolveIOServer.getClientName()})),c.id_socket=(0,mongo_manager_1.objectIdHexString)(),c.retryCnt=0,t._websocketManager.addWebSocket(c),t._subscriptionManager.createLoggedInUser(c.id_socket).then(function(){setTimeout(function(){c.pingTime=new Date,c.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(c))})},5e3)}),"DEBUG"===t.LOGGER&&console.log("Connection from: "+e.user),c.isAlive=!0,c.on("message",function(l){return __awaiter(t,void 0,void 0,function(){var r,t,n,o,s,i,a=this;return __generator(this,function(e){switch(e.label){case 0:"DEBUG"===this.LOGGER&&console.log("Message from: "+c.user,l),this._debugMsgRecv+=1,o=!1,r=[];try{r=JSON.parse(l,common_1.dateReviver)}catch(e){console.log("Error - JSON.parse",l),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+index_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([l,e])),o=!0}if(o)return[3,8];if("string"==typeof r&&"ping"===r)c&&c.readyState===c.OPEN&&c.send("pong",function(e){e&&(a._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Pong"),a.unsubscribeWS(c))});else if("string"==typeof r&&"pong"===r)c.isAlive=!0,c.pongTime=new Date,c.latency=moment.duration(moment(c.pongTime).diff(c.pingTime)).asMilliseconds(),this._subscriptionManager.loggedInLatency(c);else{if(Array.isArray(r[0]))return[3,1];console.log("Invalid message format, expected array:",r)}return[2];case 1:e.trys.push([1,6,7,8]),t=__values(r),n=t.next(),e.label=2;case 2:return n.done?[3,5]:(o=n.value,[4,this.processSocketMessage(c,o)]);case 3:e.sent(),e.label=4;case 4:return n=t.next(),[3,2];case 5:return[3,8];case 6:return s=e.sent(),s={error:s},[3,8];case 7:try{n&&!n.done&&(i=t.return)&&i.call(t)}finally{if(s)throw s.error}return[7];case 8:return[2]}})})}).on("end",function(){t.unsubscribeWS(c),t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS End")}).on("close",function(){t.unsubscribeWS(c),t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS Close")}).on("error",function(e){t.unsubscribeWS(c),t._subscriptionManager.getEnableDebug()&&console.log(new Date,c.user,c.id_socket,"WS Error")})}),setInterval(function(){t._serverWSS.clients.forEach(function(r){r.pingTime&&2e4<=Date.now()-r.pingTime.getTime()&&(!1===r.isAlive?(r.retryCnt++,3<=r.retryCnt?t.unsubscribeWS(r):(r.pingTime=new Date,r.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(r))}))):(r.retryCnt=0,r.isAlive=!1,r.pingTime=new Date,r.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(r))})))})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(f,m){return __awaiter(this,void 0,void 0,function(){var r,t,n,o,s,i,a,l,c,u,_,g,d,h,p,v;return __generator(this,function(e){switch(e.label){case 0:return(r=m[0],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||f.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||f.doc_user.roles.super_admin)?(a=m[1],t=m[2],"subscription"!==(n=m[3])?[3,1]:(i=m[4],l=m[5],"sub"===i?this._subscriptionManager.subscribe(r,a,f,t,l,m.slice(6)):this._subscriptionManager.unsubscribe(r,a,f,t,l,m.slice(6)),[3,11])):[2];case 1:if(this.publicProgram||"offline"!==n)return[3,10];h={messageId:t,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,h),this._offlineUpdates.push(f),o=m[4],s=0,e.label=2;case 2:if(!(s<o.length))return[3,9];if(i=o[s],c=i.data,c.shift(),c.shift(),a=c.shift(),c.shift(),g=c.shift(),d=(0,mongo_manager_1.objectIdHexString)(),l={messageId:a,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,l),"insertDocument"===g&&"driver-gps"===c[0])return[3,8];if("https://resolveio.com"!==index_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==index_1.ResolveIOServer.getServerConfig().ROOT_URL?index_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log-method-latency",date:new Date,data:{_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}}):log_method_latency_collection_1.LogMethodLatencies.create({_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}),"reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(c))<2e5?JSON.stringify(c,null,2):"Too Big",method:g,id_user:f.id_user||"",user:f.user||"",messageId:t,route:r}),!this._methodManager._methods[g])return[3,7];e.label=3;case 3:return e.trys.push([3,5,,6]),[4,(p=this._methodManager.callMethodInternal).call.apply(p,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:f.id_user,user:f.user,id_ws:f.id_socket}),g],__read(c),!1))];case 4:return e.sent(),[3,6];case 5:return p=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(p,null,2)),[3,6];case 6:return"updateDocumentOffline"!==g&&"updateDocumentPropsOffline"!==g||index_1.ResolveIOServer.getMongoManager().invalidateQueryCache(c[0]),[3,8];case 7:console.log("Offline - Could not find method: "+g),e.label=8;case 8:return s++,[3,2];case 9:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(f.id_socket),1),[3,11];case 10:if(c=__spreadArray([],__read(m),!1),v=c.shift(),u=c.shift(),_=c.shift(),"method"===c.shift()){if(g=c.shift(),f.user_readonly)return[2];d=(0,mongo_manager_1.objectIdHexString)(),"https://resolveio.com"!==index_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==index_1.ResolveIOServer.getServerConfig().ROOT_URL?index_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log-method-latency",date:new Date,data:{_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}}):log_method_latency_collection_1.LogMethodLatencies.create({_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}),"reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g&&log_collection_1.Logs.insertOne({_id:(0,mongo_manager_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(c))<2e5?JSON.stringify(c,null,2):"Too Big",method:g,id_user:f.id_user||"",user:f.user||"",messageId:_,route:v}),h={messageId:_,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,h),this._methodManager._methods[g]?(v=this._methodManager).callMethod.apply(v,__spreadArray([d,f,u,_,g],__read(c),!1)):console.log("Could not find method: "+g)}e.label=11;case 11:return[2]}})})},ResolveIOMainServer.prototype.unsubscribeWS=function(e){this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",e.user,e.id_socket),this._subscriptionManager.unsubscribeAll(e),e.removeAllListeners()},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return index_1.ResolveIOServer.getServerConfig()},ResolveIOMainServer}();exports.default=ResolveIOMainServer;
1
+ "use strict";var __awaiter=this&&this.__awaiter||function(e,o,s,n){return new(s=s||Promise)(function(t,r){function fulfilled(e){try{step(n.next(e))}catch(e){r(e)}}function rejected(e){try{step(n.throw(e))}catch(e){r(e)}}function step(e){var r;e.done?t(e.value):((r=e.value)instanceof s?r:new s(function(e){e(r)})).then(fulfilled,rejected)}step((n=n.apply(e,o||[])).next())})},__generator=this&&this.__generator||function(o,s){var n,i,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},c={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c;function verb(t){return function(e){var r=[t,e];if(n)throw new TypeError("Generator is already executing.");for(;l=c&&r[c=0]?0:l;)try{if(n=1,i&&(a=2&r[0]?i.return:r[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,r[1])).done)return a;switch(i=0,(r=a?[2&r[0],a.value]:r)[0]){case 0:case 1:a=r;break;case 4:return l.label++,{value:r[1],done:!1};case 5:l.label++,i=r[1],r=[0];continue;case 7:r=l.ops.pop(),l.trys.pop();continue;default:if(!(a=0<(a=l.trys).length&&a[a.length-1])&&(6===r[0]||2===r[0])){l=0;continue}if(3===r[0]&&(!a||r[1]>a[0]&&r[1]<a[3]))l.label=r[1];else if(6===r[0]&&l.label<a[1])l.label=a[1],a=r;else{if(!(a&&l.label<a[2])){a[2]&&l.ops.pop(),l.trys.pop();continue}l.label=a[2],l.ops.push(r)}}r=s.call(o,l)}catch(e){r=[6,e],i=0}finally{n=a=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}}},__values=this&&this.__values||function(e){var r="function"==typeof Symbol&&Symbol.iterator,t=r&&e[r],o=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},__read=this&&this.__read||function(e,r){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var o,s,n=t.call(e),i=[];try{for(;(void 0===r||0<r--)&&!(o=n.next()).done;)i.push(o.value)}catch(e){s={error:e}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return i},__spreadArray=this&&this.__spreadArray||function(e,r,t){if(t||2===arguments.length)for(var o,s=0,n=r.length;s<n;s++)!o&&s in r||((o=o||Array.prototype.slice.call(r,0,s))[s]=r[s]);return e.concat(o||Array.prototype.slice.call(r))},http_1=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResolveIOMainServer=void 0,require("http")),express=require("express"),bodyParser=require("body-parser"),xmlParser=require("express-xml-bodyparser"),WebSocket=require("ws"),jwt=require("jsonwebtoken"),moment=require("moment-timezone"),common_1=require("./util/common"),cron_manager_1=require("./managers/cron.manager"),method_manager_1=require("./managers/method.manager"),subscription_manager_1=require("./managers/subscription.manager"),monitor_manager_1=require("./managers/monitor.manager"),log_collection_1=require("./collections/log.collection"),log_method_latency_collection_1=require("./collections/log-method-latency.collection"),user_collection_1=require("./collections/user.collection"),home_1=require("./http/home"),auth_1=require("./http/auth"),health_1=require("./http/health"),mongodb_1=require("mongodb"),worker_task_request_collection_1=require("./collections/worker-task-request.collection"),worker_task_response_collection_1=require("./collections/worker-task-response.collection"),websocket_manager_1=require("./managers/websocket.manager"),resolveio_server_app_1=require("./resolveio-server-app"),ResolveIOMainServer=function(){function ResolveIOMainServer(){this._offlineUpdates=[],this.sesMail=!1,this.standardProgram=!1,this.publicProgram=!1,this._rebootFlag=!1,this.LOGGER="ERROR",this._clientRoutes=[],this._lastErrorMsg=null,this._debugMsgRecv=0,this._debugMsgQueue=0,this._isWorkersEnabled=!1,this._isWorkerInstance=!1,this._workerTasks=[],this._safeShutdown=!1,this._serverStartTime=new Date,this._lastErrorMsg=null,this._monitorManager=new monitor_manager_1.MonitorManager,this._monitorManagerFunction=new monitor_manager_1.MonitorManagerFunction}return ResolveIOMainServer.prototype.initServerApp=function(){var e=this;this._isWorkersEnabled="true"===process.env.IS_WORKERS_ENABLED,this._isWorkerInstance="true"===process.env.IS_WORKER_INSTANCE,setInterval(function(){e._subscriptionManager&&e._subscriptionManager.getEnableDebug()&&(console.log(new Date,"Server App","Msg Recv Hits",e._debugMsgRecv),console.log(new Date,"Server App","Msg Queue Hits",e._debugMsgQueue)),e._debugMsgQueue=0,e._debugMsgRecv=0},6e4),process.on("unhandledRejection",function(o,s){return __awaiter(e,void 0,void 0,function(){var r,t=this;return __generator(this,function(e){switch(e.label){case 0:return o&&"MongoError"===o.name&&48===o.code?[2]:(console.error(new Date,"Unhandled Rejection at Promise",[o,s]),r=moment().diff(this._serverStartTime,"seconds"),o&&("MongoNetworkTimeoutError"===o.name||o instanceof mongodb_1.MongoNetworkTimeoutError)?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - MongoNetworkTimeoutError - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify({name:o.name,message:o.message,stack:o.stack},null,2))]):[3,2]:[3,3]);case 1:e.sent(),process.exit(1),e.label=2;case 2:return[3,10];case 3:return o&&"MongoError"===o.name&&"not master"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,5]:[3,6];case 4:e.sent(),e.label=5;case 5:return process.exit(1),[3,10];case 6:return o&&"MongoError"===o.name&&"not master and slaveOk=false"===o.message?60<r&&!this._lastErrorMsg?(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - Quitting NodeJS - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))]):[3,8]:[3,9];case 7:e.sent(),e.label=8;case 8:return process.exit(1),[3,10];case 9:o&&"StatusError"!==o.name&&""!==o.message&&60<r&&!this._lastErrorMsg&&(this._lastErrorMsg=new Date,setTimeout(function(){t._lastErrorMsg=null},6e4),this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Rejection - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([o.name,o.message,o.stack],null,2))),e.label=10;case 10:return[2]}})})}),process.on("uncaughtException",function(t){return __awaiter(e,void 0,void 0,function(){var r=this;return __generator(this,function(e){switch(e.label){case 0:return(console.error(t,"Uncaught Exception thrown"),60<moment().diff(this._serverStartTime,"seconds")&&!this._lastErrorMsg)?(this._lastErrorMsg=new Date,setTimeout(function(){r._lastErrorMsg=null},6e4),[4,this._methodManager.sendEmail("dev@resolveio.com","SERVER - Unhandled Exception - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([t.name,t.message,t.stack],null,2))]):[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}})})}),process.on("SIGINT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGTERM",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),process.on("SIGQUIT",function(){e._rebootFlag=!0,e._serverHTTP&&e._serverHTTP.close(),e.safeShutdown()}),"DEBUG"===this.LOGGER&&console.log("Starting ResolveIO Server"),this._isWorkersEnabled?this._isWorkerInstance?(console.log("Running as a Worker instance"),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._cronManager=new cron_manager_1.CronManager,this.startWorkerInstance()):(console.log("Running as a Server instance"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this.listen()):(console.log("Running with Workers Disabled"),this._websocketManager=new websocket_manager_1.WebSocketManager(this),this.startServerInstance(),this._methodManager=new method_manager_1.MethodManager(this._monitorManagerFunction,this._isWorkersEnabled,this._isWorkerInstance),this._subscriptionManager=new subscription_manager_1.SubscriptionManager(this._serverWSS,resolveio_server_app_1.ResolveIOServer.getServerConfig(),this._monitorManagerFunction),this._cronManager=new cron_manager_1.CronManager,this.listen())},ResolveIOMainServer.prototype.startServerInstance=function(){this._app=express(),this._app.use(bodyParser.json({limit:"50mb",reviver:common_1.dateReviver})),this._app.use(bodyParser.urlencoded({limit:"50mb",extended:!0,parameterLimit:1e6})),this._app.use(xmlParser()),this._portHTTP=process.env.PORT_HTTP||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_HTTP||8080,this._portWSS=process.env.PORT_WSS||resolveio_server_app_1.ResolveIOServer.getServerConfig().PORT_WSS||8081,"DEBUG"===this.LOGGER&&console.log("Setup ports"),this.createServer(),"DEBUG"===this.LOGGER&&console.log("Create server"),this._app.use(function(e,r,t){r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST"),r.setHeader("Access-Control-Allow-Headers","X-Requested-With,content-type"),r.setHeader("Access-Control-Allow-Credentials","false"),t()}),"DEBUG"===this.LOGGER&&console.log("Setup cors"),(0,auth_1.setupAuthRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),(0,health_1.setupHealthRoutes)(this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"ResolveIO"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&!this.standardProgram||(0,home_1.setupHomeRoutes)(this,this._app,resolveio_server_app_1.ResolveIOServer.getServerConfig()),"DEBUG"===this.LOGGER&&console.log("Setup express routes")},ResolveIOMainServer.prototype.startWorkerInstance=function(){return __awaiter(this,void 0,void 0,function(){var r,t,o,s,n,i,a,l=this;return __generator(this,function(e){switch(e.label){case 0:return console.log("Worker instance started, watching worker-task-reqs..."),(r=worker_task_request_collection_1.WorkerTaskRequests.watchCollection([{$match:{"fullDocument.status":"pending"}}],{fullDocument:"updateLookup"})).on("change",function(s){return __awaiter(l,void 0,void 0,function(){var r,t,o=this;return __generator(this,function(e){return"insert"===s.operationType?(r=s.fullDocument)&&setTimeout(function(){o.processTask(r)},25*this._workerTasks.length):"update"===s.operationType&&(t=s.fullDocument)&&"pending"===t.status&&setTimeout(function(){o.processTask(t)},25*this._workerTasks.length),[2]})})}),r.on("error",function(e){console.error("Error in change stream worker task requests:",e),r&&r.close()}),r.on("close",function(){console.log("Change stream worker task requests closed. Restarting..."),setTimeout(function(){return l.startWorkerInstance()},5e3)}),[4,worker_task_request_collection_1.WorkerTaskRequests.find({status:"pending"},{sort:{createdAt:1}})];case 1:t=e.sent();try{for(o=__values(t),s=o.next();!s.done;s=o.next())n=s.value,this.processTask(n)}catch(e){i={error:e}}finally{try{s&&!s.done&&(a=o.return)&&a.call(o)}finally{if(i)throw i.error}}return[2]}})})},ResolveIOMainServer.prototype.processTask=function(s){return __awaiter(this,void 0,void 0,function(){var r=this;return __generator(this,function(e){return this._workerTasks.includes(s._id)||worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:s._id,status:"pending"},{$set:{status:"processing"}}).then(function(o){return __awaiter(r,void 0,void 0,function(){var r,t;return __generator(this,function(e){switch(e.label){case 0:if(!o)return[3,5];this._workerTasks.push(s._id),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,(t=this._methodManager.callMethodInternal).call.apply(t,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:s.id_user,user:s.user,id_ws:s.id_ws}),s.method],__read(s.params),!1))];case 2:return t=e.sent(),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:s._id,has_error:!1,data:t,id_user:s.id_user,user:s.user,id_ws:s.id_ws}),[3,4];case 3:return r=e.sent(),console.error("Worker failed to process task:",s._id,r),worker_task_response_collection_1.WorkerTaskResponses.create({id_request:s._id,has_error:!0,data:r.message,id_user:s.id_user,user:s.user,id_ws:s.id_ws}),[3,4];case 4:this._workerTasks.includes(s._id)&&this._workerTasks.splice(this._workerTasks.indexOf(s._id),1),worker_task_request_collection_1.WorkerTaskRequests.updateOne({_id:s._id},{$set:{status:"complete"}}),e.label=5;case 5:return[2]}})})},function(){}),[2]})})},ResolveIOMainServer.prototype.safeShutdown=function(){var e=this;this._safeShutdown||console.log(new Date,"Safe Shutdown Command Received"),this._monitorManagerFunction.getActiveMonitorFunctions().length||this._offlineUpdates.length?(this._safeShutdown||(this._safeShutdown=!0,setTimeout(function(){e._safeShutdown=!1},1e3),console.log(new Date,"Safe Exit In Progress",this._monitorManagerFunction.getActiveMonitorFunctions().length,this._offlineUpdates.length)),setImmediate(function(){e.safeShutdown()})):resolveio_server_app_1.ResolveIOServer.getMongoConnection()?resolveio_server_app_1.ResolveIOServer.getMongoConnection().close(!1).then(function(){console.log(new Date,"Safe Exit Complete, Process Exit"),process.exit(0)},function(){process.exit(1)}):process.exit(0)},ResolveIOMainServer.prototype.getIsWorkersEnabled=function(){return this._isWorkersEnabled},ResolveIOMainServer.prototype.getIsWorkerInstance=function(){return this._isWorkerInstance},ResolveIOMainServer.prototype.getWSList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_socket)}),r},ResolveIOMainServer.prototype.getWSUserList=function(){var r=[];return this._serverWSS.clients.forEach(function(e){r.push(e.id_user)}),r},ResolveIOMainServer.prototype.getHTTPServer=function(){return this._serverHTTP},ResolveIOMainServer.prototype.getCronManager=function(){return this._cronManager},ResolveIOMainServer.prototype.getMethodManager=function(){return this._methodManager},ResolveIOMainServer.prototype.getSubscriptionManager=function(){return this._subscriptionManager},ResolveIOMainServer.prototype.getMonitorManager=function(){return this._monitorManager},ResolveIOMainServer.prototype.getRebootFlag=function(){return this._rebootFlag},ResolveIOMainServer.prototype.getWebSocketManager=function(){return this._websocketManager},ResolveIOMainServer.prototype.createServer=function(){var e=this;this._serverHTTP=(0,http_1.createServer)(this._app),this._serverHTTP.keepAliveTimeout=65e3,this._serverHTTP.headersTimeout=66e3,this._serverWSS=new WebSocket.Server({port:this._portWSS,verifyClient:this.publicProgram?null:function(n,i){return __awaiter(e,void 0,void 0,function(){var r,s=this;return __generator(this,function(e){return this._rebootFlag?i(!1,409,"Unable To Process"):("DEBUG"===this.LOGGER&&console.log("Verify Client",n,i),r=n.req.headers["sec-websocket-protocol"].split(/,/),(n.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL||n.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().SEC_ROOT_URL||n.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_URL||n.origin===resolveio_server_app_1.ResolveIOServer.getServerConfig().RESOLVEIO_SECONDARY_URL)&&(r=r[0])?jwt.verify(r,resolveio_server_app_1.ResolveIOServer.getServerConfig().JWT_SECRET,function(t,o){return __awaiter(s,void 0,void 0,function(){var r;return __generator(this,function(e){switch(e.label){case 0:return t?(i(!1,401,"Unauthorized"),[3,5]):[3,1];case 1:n.req.id_user=o.id_user,e.label=2;case 2:return e.trys.push([2,4,,5]),[4,user_collection_1.Users.findById(o.id_user)];case 3:return(r=e.sent())?(n.req.user=r.fullname,n.req.user_readonly=r.readonly||!1,n.req.doc_user=r,i(!0)):i(!1),[3,5];case 4:return e.sent(),i(!1),[3,5];case 5:return[2]}})})}):i(!1,401,"Unauthorized")),[2]})})}})},ResolveIOMainServer.prototype.listen=function(){var t=this;this._serverHTTP.listen(this._portHTTP,function(){console.log("Running server on port %s",t._portHTTP)}),this._serverWSS.on("listening",function(){console.log("Running server on port %s",t._portWSS)}),this._serverWSS.on("connection",function(c,e){t.publicProgram||(c.id_user=e.id_user,c.user=e.user,c.user_readonly=e.user_readonly,c.doc_user=e.doc_user,"Admin"!==c.user&&"ResolveIO"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME&&t.getMethodManager().callMethodInternal.call(t.getMethodManager(),"supportCreateBillingUser",{id_user:c.id_user,user:c.user,date:new Date,client:resolveio_server_app_1.ResolveIOServer.getClientName()})),c.id_socket=(0,common_1.objectIdHexString)(),c.retryCnt=0,t._websocketManager.addWebSocket(c),t._subscriptionManager.createLoggedInUser(c.id_socket).then(function(){setTimeout(function(){c.pingTime=new Date,c.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(c))})},5e3)}),"DEBUG"===t.LOGGER&&console.log("Connection from: "+e.user),c.isAlive=!0,c.on("message",function(l){return __awaiter(t,void 0,void 0,function(){var r,t,o,s,n,i,a=this;return __generator(this,function(e){switch(e.label){case 0:"DEBUG"===this.LOGGER&&console.log("Message from: "+c.user,l),this._debugMsgRecv+=1,s=!1,r=[];try{r=JSON.parse(l,common_1.dateReviver)}catch(e){console.log("Error - JSON.parse",l),this._methodManager.sendEmail("dev@resolveio.com","SERVER - JSON Parse Error - "+resolveio_server_app_1.ResolveIOServer.getServerConfig().CLIENT_NAME,JSON.stringify([l,e])),s=!0}if(s)return[3,8];if("string"==typeof r&&"ping"===r)c&&c.readyState===c.OPEN&&c.send("pong",function(e){e&&(a._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Pong"),a.unsubscribeWS(c))});else if("string"==typeof r&&"pong"===r)c.isAlive=!0,c.pongTime=new Date,c.latency=moment.duration(moment(c.pongTime).diff(c.pingTime)).asMilliseconds(),this._subscriptionManager.loggedInLatency(c);else{if(Array.isArray(r[0]))return[3,1];console.log("Invalid message format, expected array:",r)}return[2];case 1:e.trys.push([1,6,7,8]),t=__values(r),o=t.next(),e.label=2;case 2:return o.done?[3,5]:(s=o.value,[4,this.processSocketMessage(c,s)]);case 3:e.sent(),e.label=4;case 4:return o=t.next(),[3,2];case 5:return[3,8];case 6:return n=e.sent(),n={error:n},[3,8];case 7:try{o&&!o.done&&(i=t.return)&&i.call(t)}finally{if(n)throw n.error}return[7];case 8:return[2]}})})}).on("end",function(){t.unsubscribeWS(c),t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS End")}).on("close",function(){t.unsubscribeWS(c),t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","WS Close")}).on("error",function(e){t.unsubscribeWS(c),t._subscriptionManager.getEnableDebug()&&console.log(new Date,c.user,c.id_socket,"WS Error")})}),setInterval(function(){t._serverWSS.clients.forEach(function(r){r.pingTime&&2e4<=Date.now()-r.pingTime.getTime()&&(!1===r.isAlive?(r.retryCnt++,3<=r.retryCnt?t.unsubscribeWS(r):(r.pingTime=new Date,r.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(r))}))):(r.retryCnt=0,r.isAlive=!1,r.pingTime=new Date,r.send("ping",function(e){e&&(t._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Error WS Ping"),t.unsubscribeWS(r))})))})},2e4)},ResolveIOMainServer.prototype.processSocketMessage=function(f,m){return __awaiter(this,void 0,void 0,function(){var r,t,o,s,n,i,a,l,c,u,_,g,d,p,h,v;return __generator(this,function(e){switch(e.label){case 0:return(r=m[0],this.publicProgram||!this._clientRoutes.some(function(e){return r.includes(e)})||f.doc_user.roles.groups.some(function(e){return e.views.some(function(e){return r.includes(e)||e.includes(r)})})||f.doc_user.roles.super_admin)?(a=m[1],t=m[2],"subscription"!==(o=m[3])?[3,1]:(i=m[4],l=m[5],"sub"===i?this._subscriptionManager.subscribe(r,a,f,t,l,m.slice(6)):this._subscriptionManager.unsubscribe(r,a,f,t,l,m.slice(6)),[3,11])):[2];case 1:if(this.publicProgram||"offline"!==o)return[3,10];p={messageId:t,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,p),this._offlineUpdates.push(f),s=m[4],n=0,e.label=2;case 2:if(!(n<s.length))return[3,9];if(i=s[n],c=i.data,c.shift(),c.shift(),a=c.shift(),c.shift(),g=c.shift(),d=(0,common_1.objectIdHexString)(),l={messageId:a,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,l),"insertDocument"===g&&"driver-gps"===c[0])return[3,8];if("https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log-method-latency",date:new Date,data:{_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}}):log_method_latency_collection_1.LogMethodLatencies.create({_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}),"reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g&&log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(c))<2e5?JSON.stringify(c,null,2):"Too Big",method:g,id_user:f.id_user||"",user:f.user||"",messageId:t,route:r}),!this._methodManager._methods[g])return[3,7];e.label=3;case 3:return e.trys.push([3,5,,6]),[4,(h=this._methodManager.callMethodInternal).call.apply(h,__spreadArray([Object.assign({},this._methodManager,method_manager_1.MethodManager.prototype,{id_user:f.id_user,user:f.user,id_ws:f.id_socket}),g],__read(c),!1))];case 4:return e.sent(),[3,6];case 5:return h=e.sent(),console.log(new Date,"Offline Error",JSON.stringify(h,null,2)),[3,6];case 6:return"updateDocumentOffline"!==g&&"updateDocumentPropsOffline"!==g||resolveio_server_app_1.ResolveIOServer.getMongoManager().invalidateQueryCache(c[0]),[3,8];case 7:console.log("Offline - Could not find method: "+g),e.label=8;case 8:return n++,[3,2];case 9:return this._offlineUpdates.splice(this._offlineUpdates.map(function(e){return e.id_socket}).indexOf(f.id_socket),1),[3,11];case 10:if(c=__spreadArray([],__read(m),!1),v=c.shift(),u=c.shift(),_=c.shift(),"method"===c.shift()){if(g=c.shift(),f.user_readonly)return[2];d=(0,common_1.objectIdHexString)(),"https://resolveio.com"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL&&"http://localhost:4200"!==resolveio_server_app_1.ResolveIOServer.getServerConfig().ROOT_URL?resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({type:"log-method-latency",date:new Date,data:{_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}}):log_method_latency_collection_1.LogMethodLatencies.create({_id:d,__v:0,date_start:new Date,date_end:null,latency_ms:0,method:g}),"reportBuilderGetResults"!==g&&"reportBuilderGetDistinctValue"!==g&&"reportBuilderBuildTree"!==g&&"generatePDF"!==g&&"getWOOfflineData"!==g&&"countQuery"!==g&&"countWithQuery"!==g&&"countCollectionWithQuery"!==g&&"find"!==g&&"findOne"!==g&&"findWithOptions"!==g&&"getDrivers"!==g&&"processAirdropDistribution"!==g&&log_collection_1.Logs.insertOne({_id:(0,common_1.objectIdHexString)(),type:"client-request",collection:"",id_document:"",payload:(0,common_1.getBinarySize)(JSON.stringify(c))<2e5?JSON.stringify(c,null,2):"Too Big",method:g,id_user:f.id_user||"",user:f.user||"",messageId:_,route:v}),p={messageId:_,hasError:!1,data:"ACK"},f&&f.readyState===f.OPEN&&this._websocketManager.send(f,p),this._methodManager._methods[g]?(v=this._methodManager).callMethod.apply(v,__spreadArray([d,f,u,_,g],__read(c),!1)):console.log("Could not find method: "+g)}e.label=11;case 11:return[2]}})})},ResolveIOMainServer.prototype.unsubscribeWS=function(e){this._subscriptionManager.getEnableDebug()&&console.log(new Date,"Server App","Unsub WS",e.user,e.id_socket),this._subscriptionManager.unsubscribeAll(e),e.removeAllListeners()},ResolveIOMainServer.prototype.getApp=function(){return this._app},ResolveIOMainServer.prototype.getServerConfig=function(){return resolveio_server_app_1.ResolveIOServer.getServerConfig()},ResolveIOMainServer}();exports.ResolveIOMainServer=ResolveIOMainServer;
2
2
  //# sourceMappingURL=server-app.js.map
package/server-app.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/server-app.ts"],"names":["http_1","require","express","bodyParser","xmlParser","WebSocket","jwt","moment","common_1","mongo_manager_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","log_collection_1","log_method_latency_collection_1","user_collection_1","home_1","auth_1","health_1","index_1","mongodb_1","worker_task_request_collection_1","worker_task_response_collection_1","websocket_manager_1","ResolveIOMainServer","_this","this","_offlineUpdates","sesMail","standardProgram","publicProgram","_rebootFlag","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_workerTasks","_safeShutdown","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","setTimeout","_methodManager","sendEmail","ResolveIOServer","getServerConfig","JSON","stringify","name","message","stack","_a","sent","exit","_serverHTTP","close","safeShutdown","MethodManager","_cronManager","CronManager","startWorkerInstance","_websocketManager","WebSocketManager","startServerInstance","SubscriptionManager","_serverWSS","listen","prototype","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","PORT_HTTP","_portWSS","PORT_WSS","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","changeStream","WorkerTaskRequests","watchCollection","$match","fullDocument.status","fullDocument","change","operationType","task_1","processTask","length","task_2","status","find","sort","createdAt","pendingTasks","_b","pendingTasks_1","__values","pendingTasks_1_1","done","task","value","includes","_id","updateOne","$set","then","resReq","push","callMethodInternal","call","apply","__spreadArray","Object","assign","id_user","user","id_ws","method","__read","params","result","WorkerTaskResponses","create","id_request","has_error","data","err_1","splice","indexOf","getActiveMonitorFunctions","setImmediate","getMongoConnection","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","ws","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","infoData","headers","split","origin","token","verify","err","decoded","Users","findById","fullname","readonly","date","client","getClientName","objectIdHexString","addWebSocket","createLoggedInUser","send","unsubscribeWS","parseErrorFound","socketData","parse","e","readyState","OPEN","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","socketData_1_1","message_1","processSocketMessage","now","getTime","messageRoute","some","a","roles","groups","views","b","super_admin","messageDate","messageId","type","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","shift","updateMessageId","methodLatencyId","serverResMethod","getLocalLogManager","writeLog","__v","date_start","date_end","latency_ms","LogMethodLatencies","Logs","insertOne","collection","id_document","payload","getBinarySize","route","_methods","_c","err_3","getMongoManager","invalidateQueryCache","map","messageRoute_1","messageDate_1","messageId_1","callMethod","unsubscribeAll","removeAllListeners","getApp"],"mappings":"+xEAAAA,Q,uDAAAC,QAAA,MAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,WAAAF,QAAA,aAAA,EACAG,UAAAH,QAAA,wBAAA,EACAI,UAAAJ,QAAA,IAAA,EACAK,IAAAL,QAAA,cAAA,EAEAM,OAAAN,QAAA,iBAAA,EAEAO,SAAAP,QAAA,eAAA,EAEAQ,gBAAAR,QAAA,0BAAA,EACAS,eAAAT,QAAA,yBAAA,EACAU,iBAAAV,QAAA,2BAAA,EACAW,uBAAAX,QAAA,iCAAA,EACAY,kBAAAZ,QAAA,4BAAA,EAGAa,iBAAAb,QAAA,8BAAA,EACAc,gCAAAd,QAAA,6CAAA,EACAe,kBAAAf,QAAA,+BAAA,EAEAgB,OAAAhB,QAAA,aAAA,EACAiB,OAAAjB,QAAA,aAAA,EACAkB,SAAAlB,QAAA,eAAA,EACAmB,QAAAnB,QAAA,SAAA,EACAoB,UAAApB,QAAA,SAAA,EACAqB,iCAAArB,QAAA,8CAAA,EACAsB,kCAAAtB,QAAA,+CAAA,EAEAuB,oBAAAvB,QAAA,8BAAA,EAEAwB,oBAAA,WAkCC,SAAAA,sBAAA,IAAAC,EAAAC,KA5BQA,KAAAC,gBAAkB,GACnBD,KAAAE,QAAU,CAAA,EACTF,KAAAG,gBAAkB,CAAA,EAClBH,KAAAI,cAAgB,CAAA,EAChBJ,KAAAK,YAAc,CAAA,EAEdL,KAAAM,OAAS,QAQTN,KAAAO,cAA0B,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,KAAM,CAAC,EAAI,UACxFR,OAAQA,EACRH,QAASuB,EAAY,SAAK,GAC1BtB,KAAMsB,EAAS,MAAK,GACpB8D,UAAWsC,EACXT,MAAOO,C,CACP,EAGE7B,EAAiC,CACpCP,UAAWsC,EACX9B,SAAU,CAAA,EACVlF,KAAM,K,EAGHY,GAAMA,EAAGwC,aAAexC,EAAGyC,MAC9B1L,KAAKyD,kBAAkB0H,KAAKlC,EAAIqE,CAAS,EAGtCtN,KAAKsC,eAAeuM,SAAShH,IAChCvB,EAAAtG,KAAKsC,gBAAegN,WAAUhI,MAAAhB,EAAAiB,cAAA,CAACsG,EAAiB5E,EAAImG,EAAaC,EAAWxH,GAAMC,OAAKO,CAAI,EAAA,CAAA,CAAA,CAAA,EAG3FzG,QAAQC,IAAI,0BAA4BgG,CAAM,C,oCAoB3C/H,oBAAAiE,UAAAqH,cAAP,SAAqBnC,GAChBjJ,KAAK0B,qBAAqBC,eAAc,GAC3CC,QAAQC,IAAI,IAAIb,KAAQ,aAAc,WAAYiI,EAAS,KAAGA,EAAc,SAAC,EAE9EjJ,KAAK0B,qBAAqB6N,eAAetG,CAAE,EAC3CA,EAAGuG,mBAAkB,CAEtB,EAEO1P,oBAAAiE,UAAA0L,OAAP,WACC,OAAOzP,KAAKgE,IACb,EAEOlE,oBAAAiE,UAAAtB,gBAAP,WACC,OAAOhD,QAAA+C,gBAAgBC,gBAAe,CACvC,EACD3C,mBAAA,EAAC","file":"server-app.js","sourcesContent":["import { createServer, Server } from 'http';\nimport * as express from 'express';\nimport * as bodyParser from 'body-parser';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport * as WebSocket from 'ws';\nimport * as jwt from 'jsonwebtoken';\n// import * as SegfaultHandler from 'segfault-handler';\nimport * as moment from 'moment-timezone';\n\nimport { dateReviver, getBinarySize } from './util/common';\n\nimport { objectIdHexString } from './managers/mongo.manager';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\n\nimport { ServerResponseModel } from './models/server-response.model';\nimport { Logs } from './collections/log.collection';\nimport { LogMethodLatencies } from './collections/log-method-latency.collection';\nimport { Users } from './collections/user.collection';\n\nimport { setupHomeRoutes } from './http/home';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { ResolveIOServer } from './index';\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { WorkerTaskRequests } from './collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from './collections/worker-task-response.collection';\nimport { WorkerTaskRequestModel } from './models/worker-task-request.model';\nimport { WebSocketManager } from './managers/websocket.manager';\n\nexport default class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _portWSS: number;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\tprivate _workerTasks: string[] = [];\n\n\tprivate _safeShutdown = false;\n\n\tconstructor() {\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager();\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && error['code'] === 48) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (error && (error['name'] === 'MongoNetworkTimeoutError' || error instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconsole.error(error, 'Uncaught Exception thrown');\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n if (this._isWorkersEnabled) {\n if (this._isWorkerInstance) {\n console.log('Running as a Worker instance');\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n this._cronManager = new CronManager();\n\t\t\t\tthis.startWorkerInstance();\n }\n\t\t\telse {\n console.log('Running as a Server instance');\n\t\t\t\tthis._websocketManager = new WebSocketManager(this);\n this.startServerInstance();\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\t\tthis.listen();\n }\n }\n\t\telse {\n console.log('Running with Workers Disabled');\n\t\t\tthis._websocketManager = new WebSocketManager(this);\n this.startServerInstance();\n\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n this._cronManager = new CronManager();\n\t\t\tthis.listen();\n }\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\t// Use body parser for http call (login)\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.PORT_HTTP || ResolveIOServer.getServerConfig()['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || ResolveIOServer.getServerConfig()['PORT_WSS'] || 8081;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\n\t\t\t// Website you wish to allow to connect\n\t\t\t// res.setHeader('Access-Control-Allow-Origin', ResolveIOServer.getServerConfig()['ROOT_URL']);\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\n\t\t\t// Request methods you wish to allow\n\t\t\t// res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\n\t\t\t// Request headers you wish to allow\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\n\t\t\t// Set to true if you need the website to include cookies in the requests sent\n\t\t\t// to the API (e.g. in case you use sessions)\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\n\t\t\t// Pass to next layer of middleware\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\tsetupHealthRoutes(this._app, ResolveIOServer.getServerConfig());\n\n\t\tif (ResolveIOServer.getServerConfig()['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate async startWorkerInstance() {\n\t\tconsole.log('Worker instance started, watching worker-task-reqs...');\n\t\n\t\t// Now, set up the change stream to watch for new tasks\n\t\tlet changeStream = WorkerTaskRequests.watchCollection([{ $match: { 'fullDocument.status': 'pending' } }], { fullDocument: 'updateLookup' });\n\t\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert') {\n\t\t\t\tconst task = change.fullDocument;\n\t\t\t\tif (task) {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis.processTask(task);\n\t\t\t\t\t}, this._workerTasks.length * 25);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (change.operationType === 'update') {\n\t\t\t\tconst task = change.fullDocument;\n\t\t\t\tif (task && task.status === 'pending') {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis.processTask(task);\n\t\t\t\t\t}, this._workerTasks.length * 25);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\n\t\tchangeStream.on('error', (error) => {\n\t\t\tconsole.error('Error in change stream worker task requests:', error);\n\t\t\tif (changeStream) {\n\t\t\t\tchangeStream.close();\n\t\t\t}\n\t\t});\n\t\n\t\tchangeStream.on('close', () => {\n\t\t\tconsole.log('Change stream worker task requests closed. Restarting...');\n\t\t\tsetTimeout(() => this.startWorkerInstance(), 5000); // Restart after a delay\n\t\t});\n\n\t\t// First, process any existing pending tasks in the database\n\t\tconst pendingTasks = await WorkerTaskRequests.find({ status: 'pending' }, {sort: {createdAt: 1}});\n\n\t\tfor (const task of pendingTasks) {\n\t\t\tthis.processTask(task);\n\t\t}\n\t}\n\t\n\t// Process a task (handles both existing and new tasks)\n\tprivate async processTask(task: WorkerTaskRequestModel) {\n\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\treturn;\n\t\t}\n\t\t\t\n\t\tWorkerTaskRequests.updateOne({ _id: task._id, status: 'pending' }, { $set: { status: 'processing' } }).then(async resReq => {\n\t\t\tif (resReq) {\n\t\t\t\tthis._workerTasks.push(task._id);\n\n\t\t\t\ttry {\n\t\t\t\t\t// Run the actual method\n\t\t\t\t\tconst result = await this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, MethodManager.prototype, { id_user: task.id_user, user: task.user, id_ws: task.id_ws }), task.method, ...task.params);\n\n\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\thas_error: false,\n\t\t\t\t\t\tdata: result,\n\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.error('Worker failed to process task:', task._id, err);\n\n\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\thas_error: true,\n\t\t\t\t\t\tdata: err.message,\n\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\t\t\tthis._workerTasks.splice(this._workerTasks.indexOf(task._id), 1);\n\t\t\t\t}\n\n\t\t\t\t// Mark the task as complete\n\t\t\t\tWorkerTaskRequests.updateOne({ _id: task._id }, { $set: { status: 'complete' } });\n\n\t\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'Complete Task', 'Current Jobs: ' + this._workerTasks.length);\n\t\t\t}\n\t\t}, () => {});\n\t}\n\n\tprivate safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length && \n\t\t\t// (!this._monitorManagerFunction.getLastCompletedMonitorFunction() ||\n\t\t\t// Date.now() >= this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime.getTime() + 1500) &&\n\t\t\t!this._offlineUpdates.length\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}, () => {process.exit(1)});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), \n\t\t\t\t\t'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length, \n\t\t\t\t\t// this._monitorManagerFunction.getLastCompletedMonitorFunction() ? this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime : '',\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(() => {\n\t\t\t\tthis.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tgetIsWorkersEnabled() {\n\t\treturn this._isWorkersEnabled;\n\t}\n\n\tgetIsWorkerInstance() {\n\t\treturn this._isWorkerInstance;\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tpublic getWebSocketManager(): WebSocketManager {\n\t\treturn this._websocketManager;\n\t}\n\n\tprivate createServer(): void {\n\t\t// Start express server\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000; // This should be bigger than `keepAliveTimeout + your server's expected response time`\n\n\t\t// Start websocket server\n\t\t// Verify client with token before opening socket\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tport: this._portWSS,\n\t\t\tverifyClient: this.publicProgram ? null : async (info, cb) => {\n\t\t\t\tif (this._rebootFlag) {\n\t\t\t\t\tcb(false, 409, 'Unable To Process');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\t\tconsole.log('Verify Client', info, cb);\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (info.origin !== ResolveIOServer.getServerConfig()['ROOT_URL'] && info.origin !== ResolveIOServer.getServerConfig()['SEC_ROOT_URL'] && info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_URL'] && info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_SECONDARY_URL']) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, ResolveIOServer.getServerConfig()['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t// Listen to port for websocket\n\tprivate listen(): void {\n\t\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('listening', () => {\n\t\t\tconsole.log('Running server on port %s', this._portWSS);\n\t\t});\n\n\t\t// On websocket connection (already verified)\n\t\tthis._serverWSS.on('connection', (ws, req) => {\n\t\t\tif (!this.publicProgram) {\n\t\t\t\t// Get user from token\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tif (ws['user'] !== 'Admin' && ResolveIOServer.getServerConfig()['CLIENT_NAME'] !== 'ResolveIO') {\n\t\t\t\t\tthis.getMethodManager().callMethodInternal.call(this.getMethodManager(), 'supportCreateBillingUser', {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tclient: ResolveIOServer.getClientName()\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\tws['retryCnt'] = 0;\n\n\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\tthis._subscriptionManager.createLoggedInUser(ws['id_socket']).then(() => {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}, 5000);\n\t\t\t});\n\n\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\tconsole.log('Connection from: ' + req['user']);\n\t\t\t}\n\t\t\t\n\t\t\t// Use for keeping connection alive (ping/pong)\n\t\t\tws['isAlive'] = true;\n\t\t\tws.on('message', async (message: string) => {\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Message from: ' + ws['user'], message);\n\t\t\t\t}\n\n\t\t\t\tthis._debugMsgRecv += 1;\n\n\t\t\t\tlet parseErrorFound = false;\n\n\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t}\n\t\t\t\tcatch(e) {\n\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\n\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([message, e]));\n\n\t\t\t\t\tparseErrorFound = true;\n\t\t\t\t}\n\n\t\t\t\tif (!parseErrorFound) {\n\t\t\t\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send('pong', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Pong');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\t\t\t\tws['isAlive'] = true;\n\t\t\t\t\t\tws['pongTime'] = new Date();\n\t\t\t\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\t\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!Array.isArray(socketData[0])) {\n\t\t\t\t\t\t// Not an array, invalid message\n\t\t\t\t\t\tconsole.log('Invalid message format, expected array:', socketData);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tfor (let message of socketData) {\n\t\t\t\t\t\t\tawait this.processSocketMessage(ws, message);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('end', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS End');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('close', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS Close');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('error', error => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), ws['user'], ws['id_socket'], 'WS Error');\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\t});\n\n\t\t// Keep alive timer to ping/pong\n\t\tsetInterval(() => {\n\t\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\t\tif (ws['pingTime'] && Date.now() - ws['pingTime'].getTime() >= 20000) {\n\t\t\t\t\tif (ws['isAlive'] === false) {\n\t\t\t\t\t\tws['retryCnt']++;\n\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}, 20000);\n\t}\n\n\tprivate async processSocketMessage(ws: WebSocket, socketData: any[]) {\n\t\tlet messageRoute = socketData[0];\n\n\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\treturn;\n\t\t}\n\n\t\tlet messageDate = socketData[1];\n\t\tlet messageId = socketData[2];\n\t\tlet type = socketData[3];\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = socketData[4];\n\t\t\tlet pub = socketData[5];\n\n\t\t\t// Subscribe\n\t\t\tif (subType === 'sub') {\n\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t}\n\t\t\t// Unsubscribe\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t}\n\t\t}\n\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: 'ACK'\n\t\t\t};\n\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.push(ws);\n\t\t\tlet offlineUpdates = socketData[4];\n\n\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\tlet update = offlineUpdates[i];\n\n\t\t\t\tlet data = update.data;\n\n\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\tmessageId: updateMessageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverResMethod);\n\t\t\t\t}\n\n\t\t\t\tif (method === 'insertDocument' && data[0] === 'driver-gps') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t) {\n\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\ttype: 'log-method-latency',\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\tmethod: method\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t}\n\t\telse { //methods\n\t\t\tlet data = [...socketData];\n\t\t\t\n\t\t\tlet messageRoute: string = data.shift();\n\t\t\tlet messageDate: Date = data.shift();\n\t\t\tlet messageId: number = data.shift();\n\t\t\tlet type: string = data.shift();\n\n\t\t\tif (type === 'method') {\n\t\t\t\tlet method = data.shift();\n\n\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\tif (\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t) {\n\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\ttype: 'log-method-latency',\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\tmethod: method\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\tthis._methodManager.callMethod(methodLatencyId, ws, messageDate, messageId, method, ...data);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// else if (type === 'methodResponse') {\n\t\t\t// \tlet method = data.shift();\n\n\t\t\t// \tMethodResponses.findOne({ $and: [{ id_user: ws['id_user'] }, { message_id: messageId }, { method: method }, { date: messageDate }] }).then(\n\t\t\t// \t\tres => {\n\t\t\t// \t\t\tif (res) {\n\t\t\t// \t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t// \t\t\t\t\tthis._websocketManager.send(ws, res.response);\n\t\t\t// \t\t\t\t}\n\t\t\t// \t\t\t}\n\t\t\t// \t\t},\n\t\t\t// \t\terr => {}\n\t\t\t// \t);\n\t\t\t// }\n\t\t}\n\t}\n\n\tpublic unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tthis._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn ResolveIOServer.getServerConfig();\n\t}\n}"]}
1
+ {"version":3,"sources":["../../src/server-app.ts"],"names":["http_1","require","express","bodyParser","xmlParser","WebSocket","jwt","moment","common_1","cron_manager_1","method_manager_1","subscription_manager_1","monitor_manager_1","log_collection_1","log_method_latency_collection_1","user_collection_1","home_1","auth_1","health_1","mongodb_1","worker_task_request_collection_1","worker_task_response_collection_1","websocket_manager_1","resolveio_server_app_1","ResolveIOMainServer","this","_offlineUpdates","sesMail","standardProgram","publicProgram","_rebootFlag","LOGGER","_clientRoutes","_lastErrorMsg","_debugMsgRecv","_debugMsgQueue","_isWorkersEnabled","_isWorkerInstance","_workerTasks","_safeShutdown","_serverStartTime","Date","_monitorManager","MonitorManager","_monitorManagerFunction","MonitorManagerFunction","prototype","initServerApp","_this","process","env","IS_WORKERS_ENABLED","IS_WORKER_INSTANCE","setInterval","_subscriptionManager","getEnableDebug","console","log","on","error","rej","__awaiter","diffTimeSec","diff","MongoNetworkTimeoutError","setTimeout","_methodManager","sendEmail","ResolveIOServer","getServerConfig","JSON","stringify","name","message","stack","_a","sent","exit","_serverHTTP","close","safeShutdown","MethodManager","_cronManager","CronManager","startWorkerInstance","_websocketManager","WebSocketManager","startServerInstance","SubscriptionManager","_serverWSS","listen","_app","use","json","limit","reviver","dateReviver","urlencoded","extended","parameterLimit","_portHTTP","PORT_HTTP","_portWSS","PORT_WSS","createServer","req","res","next","setHeader","setupAuthRoutes","setupHealthRoutes","setupHomeRoutes","changeStream","WorkerTaskRequests","watchCollection","$match","fullDocument.status","fullDocument","change","operationType","task_1","processTask","length","task_2","status","find","sort","createdAt","pendingTasks","_b","pendingTasks_1","__values","pendingTasks_1_1","done","task","value","includes","_id","updateOne","$set","then","resReq","push","callMethodInternal","call","apply","__spreadArray","Object","assign","id_user","user","id_ws","method","__read","params","result","WorkerTaskResponses","create","id_request","has_error","data","err_1","splice","indexOf","getActiveMonitorFunctions","setImmediate","getMongoConnection","getIsWorkersEnabled","getIsWorkerInstance","getWSList","clients","forEach","ws","getWSUserList","getHTTPServer","getCronManager","getMethodManager","getSubscriptionManager","getMonitorManager","getRebootFlag","getWebSocketManager","keepAliveTimeout","headersTimeout","Server","port","verifyClient","info","cb","infoData","headers","split","origin","token","verify","err","decoded","Users","findById","fullname","readonly","date","client","getClientName","objectIdHexString","addWebSocket","createLoggedInUser","send","unsubscribeWS","parseErrorFound","socketData","parse","e","readyState","OPEN","duration","asMilliseconds","loggedInLatency","Array","isArray","socketData_1","socketData_1_1","message_1","processSocketMessage","now","getTime","messageRoute","some","a","roles","groups","views","b","super_admin","messageDate","messageId","type","subType","pub","subscribe","slice","unsubscribe","serverRes","hasError","offlineUpdates","i","update","shift","updateMessageId","methodLatencyId","serverResMethod","getLocalLogManager","writeLog","__v","date_start","date_end","latency_ms","LogMethodLatencies","Logs","insertOne","collection","id_document","payload","getBinarySize","route","_methods","_c","err_3","getMongoManager","invalidateQueryCache","map","messageRoute_1","messageDate_1","messageId_1","callMethod","unsubscribeAll","removeAllListeners","getApp","exports"],"mappings":"+xEAAAA,Q,0FAAAC,QAAA,MAAA,GACAC,QAAAD,QAAA,SAAA,EACAE,WAAAF,QAAA,aAAA,EACAG,UAAAH,QAAA,wBAAA,EACAI,UAAAJ,QAAA,IAAA,EACAK,IAAAL,QAAA,cAAA,EAEAM,OAAAN,QAAA,iBAAA,EACAO,SAAAP,QAAA,eAAA,EACAQ,eAAAR,QAAA,yBAAA,EACAS,iBAAAT,QAAA,2BAAA,EACAU,uBAAAV,QAAA,iCAAA,EACAW,kBAAAX,QAAA,4BAAA,EAGAY,iBAAAZ,QAAA,8BAAA,EACAa,gCAAAb,QAAA,6CAAA,EACAc,kBAAAd,QAAA,+BAAA,EAEAe,OAAAf,QAAA,aAAA,EACAgB,OAAAhB,QAAA,aAAA,EACAiB,SAAAjB,QAAA,eAAA,EACAkB,UAAAlB,QAAA,SAAA,EACAmB,iCAAAnB,QAAA,8CAAA,EACAoB,kCAAApB,QAAA,+CAAA,EAEAqB,oBAAArB,QAAA,8BAAA,EACAsB,uBAAAtB,QAAA,wBAAA,EAEAuB,oBAAA,WAkCC,SAAAA,sBA5BQC,KAAAC,gBAAkB,GACnBD,KAAAE,QAAU,CAAA,EACTF,KAAAG,gBAAkB,CAAA,EAClBH,KAAAI,cAAgB,CAAA,EAChBJ,KAAAK,YAAc,CAAA,EAEdL,KAAAM,O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C,SAAS,EAAA7P,SAAA8P,eAAchM,KAAKC,UAAUyF,CAAI,CAAC,EAAI,IAAS1F,KAAKC,UAAUyF,EAAM,KAAM,CAAC,EAAI,UACxFR,OAAQA,EACRH,QAASuB,EAAY,SAAK,GAC1BtB,KAAMsB,EAAS,MAAK,GACpB8D,UAAWsC,EACXT,MAAOO,C,CACP,EAGE7B,EAAiC,CACpCP,UAAWsC,EACX9B,SAAU,CAAA,EACVlF,KAAM,K,EAGHY,GAAMA,EAAGwC,aAAexC,EAAGyC,MAC9B5L,KAAK4D,kBAAkByH,KAAKlC,EAAIqE,CAAS,EAGtCxN,KAAKyC,eAAesM,SAAShH,IAChCvB,EAAAxG,KAAKyC,gBAAe+M,WAAUhI,MAAAhB,EAAAiB,cAAA,CAACsG,EAAiB5E,EAAImG,EAAaC,EAAWxH,GAAMC,OAAKO,CAAI,EAAA,CAAA,CAAA,CAAA,EAG3FxG,QAAQC,IAAI,0BAA4B+F,CAAM,C,oCAoB3ChI,oBAAAsB,UAAAiK,cAAP,SAAqBnC,GAChBnJ,KAAK6B,qBAAqBC,eAAc,GAC3CC,QAAQC,IAAI,IAAIhB,KAAQ,aAAc,WAAYmI,EAAS,KAAGA,EAAc,SAAC,EAE9EnJ,KAAK6B,qBAAqB4N,eAAetG,CAAE,EAC3CA,EAAGuG,mBAAkB,CAEtB,EAEO3P,oBAAAsB,UAAAsO,OAAP,WACC,OAAO3P,KAAKkE,IACb,EAEOnE,oBAAAsB,UAAAuB,gBAAP,WACC,OAAO9C,uBAAA6C,gBAAgBC,gBAAe,CACvC,EACD7C,mBAAA,EAAC,EA95BY6P,QAAA7P,oBAAAA","file":"server-app.js","sourcesContent":["import { createServer, Server } from 'http';\nimport * as express from 'express';\nimport * as bodyParser from 'body-parser';\nimport * as xmlParser from 'express-xml-bodyparser';\nimport * as WebSocket from 'ws';\nimport * as jwt from 'jsonwebtoken';\n// import * as SegfaultHandler from 'segfault-handler';\nimport * as moment from 'moment-timezone';\nimport { dateReviver, getBinarySize, objectIdHexString } from './util/common';\nimport { CronManager } from './managers/cron.manager';\nimport { MethodManager } from './managers/method.manager';\nimport { SubscriptionManager } from './managers/subscription.manager';\nimport { MonitorManager, MonitorManagerFunction } from './managers/monitor.manager';\n\nimport { ServerResponseModel } from './models/server-response.model';\nimport { Logs } from './collections/log.collection';\nimport { LogMethodLatencies } from './collections/log-method-latency.collection';\nimport { Users } from './collections/user.collection';\n\nimport { setupHomeRoutes } from './http/home';\nimport { setupAuthRoutes } from './http/auth';\nimport { setupHealthRoutes } from './http/health';\nimport { MongoNetworkTimeoutError } from 'mongodb';\nimport { WorkerTaskRequests } from './collections/worker-task-request.collection';\nimport { WorkerTaskResponses } from './collections/worker-task-response.collection';\nimport { WorkerTaskRequestModel } from './models/worker-task-request.model';\nimport { WebSocketManager } from './managers/websocket.manager';\nimport { ResolveIOServer } from './resolveio-server-app';\n\nexport class ResolveIOMainServer {\n\tprivate _app: express.Application;\n\tprivate _serverHTTP: Server;\n\tprivate _portHTTP: string | number;\n\tprivate _serverWSS: WebSocket.Server;\n\tprivate _portWSS: number;\n\tprivate _offlineUpdates = [];\n\tpublic sesMail = false;\n\tprivate standardProgram = false;\n\tprivate publicProgram = false;\n\tprivate _rebootFlag = false;\n\n\tprivate LOGGER = 'ERROR'; //ERROR / DEBUG\n\n\tprivate _websocketManager: WebSocketManager;\n\tprivate _monitorManager: MonitorManager;\n\tprivate _monitorManagerFunction: MonitorManagerFunction;\n\tprivate _subscriptionManager: SubscriptionManager;\n\tprivate _methodManager: MethodManager;\n\tprivate _cronManager: CronManager;\n\tprivate _clientRoutes: string[] = [];\n\n\tprivate _serverStartTime: Date;\n\tprivate _lastErrorMsg: Date = null;\n\n\tprivate _debugMsgRecv = 0;\n\tprivate _debugMsgQueue = 0;\n\n\tprivate _isWorkersEnabled = false;\n\tprivate _isWorkerInstance = false;\n\tprivate _workerTasks: string[] = [];\n\n\tprivate _safeShutdown = false;\n\n\tconstructor() {\n\t\tthis._serverStartTime = new Date();\n\t\tthis._lastErrorMsg = null;\n\t\tthis._monitorManager = new MonitorManager();\n\t\tthis._monitorManagerFunction = new MonitorManagerFunction();\n\t}\n\n\tinitServerApp() {\n\t\t// Check for workers and decide what to start\n\t\tthis._isWorkersEnabled = process.env.IS_WORKERS_ENABLED === 'true';\n\t\tthis._isWorkerInstance = process.env.IS_WORKER_INSTANCE === 'true';\n\n\t\tsetInterval(() => {\n\t\t\tif (this._subscriptionManager && this._subscriptionManager.getEnableDebug()) {\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Recv Hits', this._debugMsgRecv);\n\t\t\t\tconsole.log(new Date(), 'Server App', 'Msg Queue Hits', this._debugMsgQueue);\n\t\t\t}\n\n\t\t\tthis._debugMsgQueue = 0;\n\t\t\tthis._debugMsgRecv = 0;\n\t\t}, 60000);\n\n\t\tprocess.on('unhandledRejection', async (error, rej) => {\n\t\t\t// Condition to filter out the MongoError with code 48 (NamespaceExists)\n\t\t\tif (error && error['name'] === 'MongoError' && error['code'] === 48) {\n\t\t\t\treturn; // Simply return without doing anything further\n\t\t\t}\n\n\t\t\t// if (error && error['name'] === 'MongoServerError') {\n\t\t\t// \treturn; // Simply return without doing anything further\n\t\t\t// }\n\n\t\t\tconsole.error(new Date(), 'Unhandled Rejection at Promise', [error, rej]);\n\t\t\t\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\t// If this is a MongoNetworkTimeoutError, handle it specifically\n\t\t\tif (error && (error['name'] === 'MongoNetworkTimeoutError' || error instanceof MongoNetworkTimeoutError)) {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t// Sending email notification (using your existing method)\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - MongoNetworkTimeoutError - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify({\n\t\t\t\t\t\tname: error['name'],\n\t\t\t\t\t\tmessage: error['message'],\n\t\t\t\t\t\tstack: error['stack']\n\t\t\t\t\t}, null, 2));\n\n\t\t\t\t\t// Exiting the process\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error && error['name'] === 'MongoError' && error['message'] === 'not master and slaveOk=false') {\n\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t}, 60000);\n\n\t\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - Quitting NodeJS - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t}\n\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t\telse if (error) {\n\t\t\t\tif (error['name'] !== 'StatusError' && error['message'] !== '') {\n\t\t\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t\t\t}, 60000);\n\n\t\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Rejection - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('uncaughtException', async error => {\n\t\t\tconsole.error(error, 'Uncaught Exception thrown');\n\n\t\t\tlet diffTimeSec = moment().diff(this._serverStartTime, 'seconds');\n\n\t\t\tif (diffTimeSec > 60 && !this._lastErrorMsg) {\n\t\t\t\tthis._lastErrorMsg = new Date();\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._lastErrorMsg = null;\n\t\t\t\t}, 60000);\n\t\t\t\t\n\t\t\t\tawait this._methodManager.sendEmail('dev@resolveio.com', 'SERVER - Unhandled Exception - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([error['name'], error['message'], error['stack']], null, 2));\n\t\t\t}\n\t\t});\n\n\t\t//PM2 wants to reboot/restart\n\t\tprocess.on('SIGINT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGTERM', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tprocess.on('SIGQUIT', () => {\n\t\t\tthis._rebootFlag = true;\n\t\t\tif (this._serverHTTP) {\n\t\t\t\tthis._serverHTTP.close();\n\t\t\t}\n\t\t\tthis.safeShutdown();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Starting ResolveIO Server');\n\t\t}\n\n if (this._isWorkersEnabled) {\n if (this._isWorkerInstance) {\n console.log('Running as a Worker instance');\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n this._cronManager = new CronManager();\n\t\t\t\tthis.startWorkerInstance();\n }\n\t\t\telse {\n console.log('Running as a Server instance');\n\t\t\t\tthis._websocketManager = new WebSocketManager(this);\n this.startServerInstance();\n\t\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n\t\t\t\tthis.listen();\n }\n }\n\t\telse {\n console.log('Running with Workers Disabled');\n\t\t\tthis._websocketManager = new WebSocketManager(this);\n this.startServerInstance();\n\t\t\tthis._methodManager = new MethodManager(this._monitorManagerFunction, this._isWorkersEnabled, this._isWorkerInstance);\n\t\t\tthis._subscriptionManager = new SubscriptionManager(this._serverWSS, ResolveIOServer.getServerConfig(), this._monitorManagerFunction);\n this._cronManager = new CronManager();\n\t\t\tthis.listen();\n }\n\t}\n\n\tprivate startServerInstance() {\n\t\t// Start express app\n\t\tthis._app = express();\n\n\t\t// Use body parser for http call (login)\n\t\tthis._app.use(bodyParser.json({limit: '50mb', reviver: dateReviver}));\n\t\tthis._app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 1000000 }));\n\t\tthis._app.use(xmlParser());\n\t\t\n\t\t// Set port\n\t\tthis._portHTTP = process.env.PORT_HTTP || ResolveIOServer.getServerConfig()['PORT_HTTP'] || 8080;\n\t\tthis._portWSS = process.env.PORT_WSS || ResolveIOServer.getServerConfig()['PORT_WSS'] || 8081;\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup ports');\n\t\t}\n\n\t\t// Create http server and websock server\n\t\tthis.createServer();\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Create server');\n\t\t}\n\n\t\t// Set CORS\n\t\tthis._app.use(function (req, res, next) {\n\n\t\t\t// Website you wish to allow to connect\n\t\t\t// res.setHeader('Access-Control-Allow-Origin', ResolveIOServer.getServerConfig()['ROOT_URL']);\n\t\t\tres.setHeader('Access-Control-Allow-Origin', '*');\n\n\t\t\t// Request methods you wish to allow\n\t\t\t// res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');\n\t\t\tres.setHeader('Access-Control-Allow-Methods', 'GET, POST');\n\n\t\t\t// Request headers you wish to allow\n\t\t\tres.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');\n\n\t\t\t// Set to true if you need the website to include cookies in the requests sent\n\t\t\t// to the API (e.g. in case you use sessions)\n\t\t\tres.setHeader('Access-Control-Allow-Credentials', 'false');\n\n\t\t\t// Pass to next layer of middleware\n\t\t\tnext();\n\t\t});\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup cors');\n\t\t}\n\n\t\t// Set up http login route\n\t\tsetupAuthRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\tsetupHealthRoutes(this._app, ResolveIOServer.getServerConfig());\n\n\t\tif (ResolveIOServer.getServerConfig()['CLIENT_NAME'] === 'ResolveIO' || this.standardProgram) {\n\t\t\tsetupHomeRoutes(this, this._app, ResolveIOServer.getServerConfig());\n\t\t}\n\n\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\tconsole.log('Setup express routes');\n\t\t}\n\t}\n\n\tprivate async startWorkerInstance() {\n\t\tconsole.log('Worker instance started, watching worker-task-reqs...');\n\t\n\t\t// Now, set up the change stream to watch for new tasks\n\t\tlet changeStream = WorkerTaskRequests.watchCollection([{ $match: { 'fullDocument.status': 'pending' } }], { fullDocument: 'updateLookup' });\n\t\n\t\tchangeStream.on('change', async (change) => {\n\t\t\tif (change.operationType === 'insert') {\n\t\t\t\tconst task = change.fullDocument;\n\t\t\t\tif (task) {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis.processTask(task);\n\t\t\t\t\t}, this._workerTasks.length * 25);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (change.operationType === 'update') {\n\t\t\t\tconst task = change.fullDocument;\n\t\t\t\tif (task && task.status === 'pending') {\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tthis.processTask(task);\n\t\t\t\t\t}, this._workerTasks.length * 25);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\n\t\tchangeStream.on('error', (error) => {\n\t\t\tconsole.error('Error in change stream worker task requests:', error);\n\t\t\tif (changeStream) {\n\t\t\t\tchangeStream.close();\n\t\t\t}\n\t\t});\n\t\n\t\tchangeStream.on('close', () => {\n\t\t\tconsole.log('Change stream worker task requests closed. Restarting...');\n\t\t\tsetTimeout(() => this.startWorkerInstance(), 5000); // Restart after a delay\n\t\t});\n\n\t\t// First, process any existing pending tasks in the database\n\t\tconst pendingTasks = await WorkerTaskRequests.find({ status: 'pending' }, {sort: {createdAt: 1}});\n\n\t\tfor (const task of pendingTasks) {\n\t\t\tthis.processTask(task);\n\t\t}\n\t}\n\t\n\t// Process a task (handles both existing and new tasks)\n\tprivate async processTask(task: WorkerTaskRequestModel) {\n\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\treturn;\n\t\t}\n\t\t\t\n\t\tWorkerTaskRequests.updateOne({ _id: task._id, status: 'pending' }, { $set: { status: 'processing' } }).then(async resReq => {\n\t\t\tif (resReq) {\n\t\t\t\tthis._workerTasks.push(task._id);\n\n\t\t\t\ttry {\n\t\t\t\t\t// Run the actual method\n\t\t\t\t\tconst result = await this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, MethodManager.prototype, { id_user: task.id_user, user: task.user, id_ws: task.id_ws }), task.method, ...task.params);\n\n\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\thas_error: false,\n\t\t\t\t\t\tdata: result,\n\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tcatch (err) {\n\t\t\t\t\tconsole.error('Worker failed to process task:', task._id, err);\n\n\t\t\t\t\tWorkerTaskResponses.create({\n\t\t\t\t\t\tid_request: task._id,\n\t\t\t\t\t\thas_error: true,\n\t\t\t\t\t\tdata: err.message,\n\t\t\t\t\t\tid_user: task.id_user,\n\t\t\t\t\t\tuser: task.user,\n\t\t\t\t\t\tid_ws: task.id_ws\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (this._workerTasks.includes(task._id)) {\n\t\t\t\t\tthis._workerTasks.splice(this._workerTasks.indexOf(task._id), 1);\n\t\t\t\t}\n\n\t\t\t\t// Mark the task as complete\n\t\t\t\tWorkerTaskRequests.updateOne({ _id: task._id }, { $set: { status: 'complete' } });\n\n\t\t\t\t// console.log(new Date(), 'Instance: ' + process.env.NODE_APP_INSTANCE, 'Complete Task', 'Current Jobs: ' + this._workerTasks.length);\n\t\t\t}\n\t\t}, () => {});\n\t}\n\n\tprivate safeShutdown() {\n\t\tif (!this._safeShutdown) {\n\t\t\tconsole.log(new Date(), 'Safe Shutdown Command Received');\n\t\t}\n\n\t\tif (\n\t\t\t!this._monitorManagerFunction.getActiveMonitorFunctions().length && \n\t\t\t// (!this._monitorManagerFunction.getLastCompletedMonitorFunction() ||\n\t\t\t// Date.now() >= this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime.getTime() + 1500) &&\n\t\t\t!this._offlineUpdates.length\n\t\t) {\n\t\t\tif (ResolveIOServer.getMongoConnection()) {\n\t\t\t\tResolveIOServer.getMongoConnection().close(false).then(() => {\n\t\t\t\t\tconsole.log(new Date(), 'Safe Exit Complete, Process Exit');\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}, () => {process.exit(1)});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (!this._safeShutdown) {\n\t\t\t\tthis._safeShutdown = true;\n\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis._safeShutdown = false;\n\t\t\t\t}, 1000);\n\n\t\t\t\tconsole.log(new Date(), \n\t\t\t\t\t'Safe Exit In Progress', \n\t\t\t\t\tthis._monitorManagerFunction.getActiveMonitorFunctions().length, \n\t\t\t\t\t// this._monitorManagerFunction.getLastCompletedMonitorFunction() ? this._monitorManagerFunction.getLastCompletedMonitorFunction().endTime : '',\n\t\t\t\t\tthis._offlineUpdates.length\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tsetImmediate(() => {\n\t\t\t\tthis.safeShutdown();\n\t\t\t});\n\t\t}\n\t}\n\n\tgetIsWorkersEnabled() {\n\t\treturn this._isWorkersEnabled;\n\t}\n\n\tgetIsWorkerInstance() {\n\t\treturn this._isWorkerInstance;\n\t}\n\n\tpublic getWSList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_socket']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getWSUserList() {\n\t\tlet res = [];\n\n\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\tres.push(ws['id_user']);\n\t\t});\n\n\t\treturn res;\n\t}\n\n\tpublic getHTTPServer() {\n\t\treturn this._serverHTTP;\n\t}\n\n\tpublic getCronManager() {\n\t\treturn this._cronManager;\n\t}\n\n\tpublic getMethodManager() {\n\t\treturn this._methodManager;\n\t}\n\n\tpublic getSubscriptionManager() {\n\t\treturn this._subscriptionManager;\n\t}\n\n\tpublic getMonitorManager() {\n\t\treturn this._monitorManager;\n\t}\n\n\tpublic getRebootFlag() {\n\t\treturn this._rebootFlag;\n\t}\n\n\tpublic getWebSocketManager(): WebSocketManager {\n\t\treturn this._websocketManager;\n\t}\n\n\tprivate createServer(): void {\n\t\t// Start express server\n\t\tthis._serverHTTP = createServer(this._app);\n\t\tthis._serverHTTP.keepAliveTimeout = 65000;\n\t\tthis._serverHTTP.headersTimeout = 66000; // This should be bigger than `keepAliveTimeout + your server's expected response time`\n\n\t\t// Start websocket server\n\t\t// Verify client with token before opening socket\n\t\tthis._serverWSS = new WebSocket.Server({\n\t\t\tport: this._portWSS,\n\t\t\tverifyClient: this.publicProgram ? null : async (info, cb) => {\n\t\t\t\tif (this._rebootFlag) {\n\t\t\t\t\tcb(false, 409, 'Unable To Process');\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\t\tconsole.log('Verify Client', info, cb);\n\t\t\t\t\t}\n\n\t\t\t\t\tlet infoData = (<string>info.req.headers['sec-websocket-protocol']).split(/,/);\n\n\t\t\t\t\tif (info.origin !== ResolveIOServer.getServerConfig()['ROOT_URL'] && info.origin !== ResolveIOServer.getServerConfig()['SEC_ROOT_URL'] && info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_URL'] && info.origin !== ResolveIOServer.getServerConfig()['RESOLVEIO_SECONDARY_URL']) {\n\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet token = infoData[0];\n\t\t\t\t\t\tif (!token) {\n\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tjwt.verify(token, ResolveIOServer.getServerConfig()['JWT_SECRET'], async (err, decoded) => {\n\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\tcb(false, 401, 'Unauthorized');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tinfo.req['id_user'] = decoded['id_user'];\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tlet user = await Users.findById(decoded['id_user']);\n\t\t\t\t\t\t\t\t\t\tif (user) {\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user'] = user.fullname;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['user_readonly'] = user.readonly || false;\n\t\t\t\t\t\t\t\t\t\t\tinfo.req['doc_user'] = user;\n\t\t\t\t\t\t\t\t\t\t\tcb(true);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\t\t\t\t\tcb(false);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\t// Listen to port for websocket\n\tprivate listen(): void {\n\t\tthis._serverHTTP.listen(this._portHTTP, () => {\n\t\t\tconsole.log('Running server on port %s', this._portHTTP);\n\t\t});\n\n\t\tthis._serverWSS.on('listening', () => {\n\t\t\tconsole.log('Running server on port %s', this._portWSS);\n\t\t});\n\n\t\t// On websocket connection (already verified)\n\t\tthis._serverWSS.on('connection', (ws, req) => {\n\t\t\tif (!this.publicProgram) {\n\t\t\t\t// Get user from token\n\t\t\t\tws['id_user'] = req['id_user'];\n\t\t\t\tws['user'] = req['user'];\n\t\t\t\tws['user_readonly'] = req['user_readonly'];\n\t\t\t\tws['doc_user'] = req['doc_user'];\n\n\t\t\t\tif (ws['user'] !== 'Admin' && ResolveIOServer.getServerConfig()['CLIENT_NAME'] !== 'ResolveIO') {\n\t\t\t\t\tthis.getMethodManager().callMethodInternal.call(this.getMethodManager(), 'supportCreateBillingUser', {\n\t\t\t\t\t\tid_user: ws['id_user'],\n\t\t\t\t\t\tuser: ws['user'],\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tclient: ResolveIOServer.getClientName()\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tws['id_socket'] = objectIdHexString();\n\t\t\tws['retryCnt'] = 0;\n\n\t\t\tthis._websocketManager.addWebSocket(ws);\n\n\t\t\tthis._subscriptionManager.createLoggedInUser(ws['id_socket']).then(() => {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}, 5000);\n\t\t\t});\n\n\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\tconsole.log('Connection from: ' + req['user']);\n\t\t\t}\n\t\t\t\n\t\t\t// Use for keeping connection alive (ping/pong)\n\t\t\tws['isAlive'] = true;\n\t\t\tws.on('message', async (message: string) => {\n\t\t\t\tif (this.LOGGER === 'DEBUG') {\n\t\t\t\t\tconsole.log('Message from: ' + ws['user'], message);\n\t\t\t\t}\n\n\t\t\t\tthis._debugMsgRecv += 1;\n\n\t\t\t\tlet parseErrorFound = false;\n\n\t\t\t\tlet socketData = [];\n\t\t\t\t\n\t\t\t\ttry {\n\t\t\t\t\tsocketData = JSON.parse(message, dateReviver);\n\t\t\t\t}\n\t\t\t\tcatch(e) {\n\t\t\t\t\tconsole.log('Error - JSON.parse', message);\n\t\t\t\t\t\n\t\t\t\t\tthis._methodManager.sendEmail('dev@resolveio.com', 'SERVER - JSON Parse Error - ' + ResolveIOServer.getServerConfig()['CLIENT_NAME'], JSON.stringify([message, e]));\n\n\t\t\t\t\tparseErrorFound = true;\n\t\t\t\t}\n\n\t\t\t\tif (!parseErrorFound) {\n\t\t\t\t\tif (typeof socketData === 'string' && socketData === 'ping') {\n\t\t\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\t\t\tws.send('pong', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Pong');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse if (typeof socketData === 'string' && socketData === 'pong') {\n\t\t\t\t\t\tws['isAlive'] = true;\n\t\t\t\t\t\tws['pongTime'] = new Date();\n\t\t\t\t\t\tws['latency'] = moment.duration(moment(ws['pongTime']).diff(ws['pingTime'])).asMilliseconds();\n\t\t\t\t\t\tthis._subscriptionManager.loggedInLatency(ws);\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!Array.isArray(socketData[0])) {\n\t\t\t\t\t\t// Not an array, invalid message\n\t\t\t\t\t\tconsole.log('Invalid message format, expected array:', socketData);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tfor (let message of socketData) {\n\t\t\t\t\t\t\tawait this.processSocketMessage(ws, message);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('end', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS End');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('close', () => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), 'Server App', 'WS Close');\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('error', error => {\n\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\tconsole.log(new Date(), ws['user'], ws['id_socket'], 'WS Error');\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\t});\n\n\t\t// Keep alive timer to ping/pong\n\t\tsetInterval(() => {\n\t\t\tthis._serverWSS.clients.forEach((ws: WebSocket) => {\n\t\t\t\tif (ws['pingTime'] && Date.now() - ws['pingTime'].getTime() >= 20000) {\n\t\t\t\t\tif (ws['isAlive'] === false) {\n\t\t\t\t\t\tws['retryCnt']++;\n\n\t\t\t\t\t\tif (ws['retryCnt'] >= 3) {\n\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tws['retryCnt'] = 0;\n\t\t\t\t\t\tws['isAlive'] = false;\n\t\t\t\t\t\tws['pingTime'] = new Date();\n\t\t\t\t\t\tws.send('ping', (error) => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\t\t\t\t\t\t\tconsole.log(new Date(), 'Server App', 'Error WS Ping');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tthis.unsubscribeWS(ws);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}, 20000);\n\t}\n\n\tprivate async processSocketMessage(ws: WebSocket, socketData: any[]) {\n\t\tlet messageRoute = socketData[0];\n\n\t\tif (!this.publicProgram && this._clientRoutes.some(a => messageRoute.includes(a)) && !ws['doc_user'].roles.groups.some(a => a.views.some(b => messageRoute.includes(b) || b.includes(messageRoute))) && !ws['doc_user'].roles.super_admin) {\n\t\t\treturn;\n\t\t}\n\n\t\tlet messageDate = socketData[1];\n\t\tlet messageId = socketData[2];\n\t\tlet type = socketData[3];\n\n\t\tif (type === 'subscription') {\n\t\t\tlet subType = socketData[4];\n\t\t\tlet pub = socketData[5];\n\n\t\t\t// Subscribe\n\t\t\tif (subType === 'sub') {\n\t\t\t\tthis._subscriptionManager.subscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t}\n\t\t\t// Unsubscribe\n\t\t\telse {\n\t\t\t\tthis._subscriptionManager.unsubscribe(messageRoute, messageDate, ws, messageId, pub, socketData.slice(6));\n\t\t\t}\n\t\t}\n\t\telse if (!this.publicProgram && type === 'offline') {\n\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\tmessageId: messageId,\n\t\t\t\thasError: false,\n\t\t\t\tdata: 'ACK'\n\t\t\t};\n\n\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.push(ws);\n\t\t\tlet offlineUpdates = socketData[4];\n\n\t\t\tfor (let i = 0; i < offlineUpdates.length; i++) {\n\t\t\t\tlet update = offlineUpdates[i];\n\n\t\t\t\tlet data = update.data;\n\n\t\t\t\tlet updateRoute = data.shift();\n\t\t\t\tlet updateDate = data.shift();\n\t\t\t\tlet updateMessageId = data.shift();\n\t\t\t\tlet updateType = data.shift();\n\t\t\t\tlet method = data.shift();\n\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\tlet serverResMethod: ServerResponseModel = {\n\t\t\t\t\tmessageId: updateMessageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverResMethod);\n\t\t\t\t}\n\n\t\t\t\tif (method === 'insertDocument' && data[0] === 'driver-gps') {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t) {\n\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\ttype: 'log-method-latency',\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\tmethod: method\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._methodManager.callMethodInternal.call(Object.assign({}, this._methodManager, MethodManager.prototype, {id_user: ws['id_user'], user: ws['user'], id_ws: ws['id_socket']}), method, ...data);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (err) {\n\t\t\t\t\t\tconsole.log(new Date(), 'Offline Error', JSON.stringify(err, null, 2));\n\t\t\t\t\t}\n\n\t\t\t\t\tif (method === 'updateDocumentOffline' || method === 'updateDocumentPropsOffline') {\n\t\t\t\t\t\tResolveIOServer.getMongoManager().invalidateQueryCache(data[0]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Offline - Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis._offlineUpdates.splice(this._offlineUpdates.map(a => a['id_socket']).indexOf(ws['id_socket']), 1);\n\t\t}\n\t\telse { //methods\n\t\t\tlet data = [...socketData];\n\t\t\t\n\t\t\tlet messageRoute: string = data.shift();\n\t\t\tlet messageDate: Date = data.shift();\n\t\t\tlet messageId: number = data.shift();\n\t\t\tlet type: string = data.shift();\n\n\t\t\tif (type === 'method') {\n\t\t\t\tlet method = data.shift();\n\n\t\t\t\tif (ws['user_readonly']) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlet methodLatencyId = objectIdHexString();\n\n\t\t\t\tif (\n\t\t\t\t\tResolveIOServer.getServerConfig()['ROOT_URL'] !== 'https://resolveio.com'\n\t\t\t\t&& ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200'\n\t\t\t\t) {\n\t\t\t\t\tResolveIOServer.getLocalLogManager().writeLog({\n\t\t\t\t\t\ttype: 'log-method-latency',\n\t\t\t\t\t\tdate: new Date(),\n\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\t\tmethod: method\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tLogMethodLatencies.create({\n\t\t\t\t\t\t_id: methodLatencyId,\n\t\t\t\t\t\t__v: 0,\n\t\t\t\t\t\tdate_start: new Date(),\n\t\t\t\t\t\tdate_end: null,\n\t\t\t\t\t\tlatency_ms: 0,\n\t\t\t\t\t\tmethod: method\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tif (method !== 'reportBuilderGetResults' && method !== 'reportBuilderGetDistinctValue' && method !== 'reportBuilderBuildTree' && method !== 'generatePDF' && method !== 'getWOOfflineData' && method !== 'countQuery' && method !== 'countWithQuery' && method !== 'countCollectionWithQuery' && method !== 'find' && method !== 'findOne' && method !== 'findWithOptions' && method !== 'getDrivers' && method !== 'processAirdropDistribution') {\n\t\t\t\t\tLogs.insertOne({\n\t\t\t\t\t\t_id: objectIdHexString(),\n\t\t\t\t\t\ttype: 'client-request',\n\t\t\t\t\t\tcollection: '',\n\t\t\t\t\t\tid_document: '',\n\t\t\t\t\t\tpayload: getBinarySize(JSON.stringify(data)) < 200000 ? JSON.stringify(data, null, 2) : 'Too Big',\n\t\t\t\t\t\tmethod: method,\n\t\t\t\t\t\tid_user: ws['id_user'] || '',\n\t\t\t\t\t\tuser: ws['user'] || '',\n\t\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\t\troute: messageRoute\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tlet serverRes: ServerResponseModel = {\n\t\t\t\t\tmessageId: messageId,\n\t\t\t\t\thasError: false,\n\t\t\t\t\tdata: 'ACK'\n\t\t\t\t};\n\n\t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t\t\tthis._websocketManager.send(ws, serverRes);\n\t\t\t\t}\n\n\t\t\t\tif (this._methodManager._methods[method]) {\n\t\t\t\t\tthis._methodManager.callMethod(methodLatencyId, ws, messageDate, messageId, method, ...data);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tconsole.log('Could not find method: ' + method);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// else if (type === 'methodResponse') {\n\t\t\t// \tlet method = data.shift();\n\n\t\t\t// \tMethodResponses.findOne({ $and: [{ id_user: ws['id_user'] }, { message_id: messageId }, { method: method }, { date: messageDate }] }).then(\n\t\t\t// \t\tres => {\n\t\t\t// \t\t\tif (res) {\n\t\t\t// \t\t\t\tif (ws && ws.readyState === ws.OPEN) {\n\t\t\t// \t\t\t\t\tthis._websocketManager.send(ws, res.response);\n\t\t\t// \t\t\t\t}\n\t\t\t// \t\t\t}\n\t\t\t// \t\t},\n\t\t\t// \t\terr => {}\n\t\t\t// \t);\n\t\t\t// }\n\t\t}\n\t}\n\n\tpublic unsubscribeWS(ws: WebSocket) {\n\t\tif (this._subscriptionManager.getEnableDebug()) {\n\t\t\tconsole.log(new Date(), 'Server App', 'Unsub WS', ws['user'], ws['id_socket']);\n\t\t}\n\t\tthis._subscriptionManager.unsubscribeAll(ws);\n\t\tws.removeAllListeners();\n\t\tws = null;\n\t}\n\n\tpublic getApp() {\n\t\treturn this._app;\n\t}\n\n\tpublic getServerConfig() {\n\t\treturn ResolveIOServer.getServerConfig();\n\t}\n}"]}
package/util/common.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { LookupTables } from '../models/report-builder.model';
2
+ export declare function objectIdHexString(): string;
2
3
  export declare function buildRbSchema(rbSchema: any): any;
3
4
  export declare function buildRbLookups(rbLookups: LookupTables[], defaultSchema: object, default_checked_array?: string[]): object;
4
5
  export declare function throwErr(err: any, lkp: any, lookupNode: any, newPropertyName?: string): void;
package/util/common.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var o,n,i=r.call(e),a=[];try{for(;(void 0===t||0<t--)&&!(o=i.next()).done;)a.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return a},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],o=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,i=t.length;n<i;n++)!o&&n in t||((o=o||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},rusDiff=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.mergeDeep=exports.isObject=exports.toTitleCase=exports.randomString=exports.pad=exports.getBinarySize=exports.deepDiffDetails=exports.applyMongoUpdate=exports.getDeepDiff=exports.mergeUpdates=exports.getMongoMergeUpdatedDoc=exports.getMongoUpdates=exports.dateReviver=exports.deepCopy=exports.floorPrecision=exports.round=exports.roundPrecision=exports.throwErr=exports.buildRbLookups=exports.buildRbSchema=void 0,require("rus-diff")),deepDiff=require("deep-diff").diff,deep_object_diff_1=require("deep-object-diff"),clone=require("clone"),moment=require("moment-timezone");function buildRbSchema(t){return Object.keys(t).forEach(function(e){t[e].type===Object?(t[e].type="Object",t[e].rbType="Object"):t[e].type===Array?(t[e].type="Array",t[e].rbType="Array"):t[e].type===String?(t[e].type="String",t[e].rbType="String"):t[e].type===Date?(t[e].type="Date",t[e].rbType="Date"):t[e].type===Number?(t[e].type="Number",t[e].rbType="Number"):t[e].type===Boolean&&(t[e].rbType="Boolean",t[e].type="Boolean")}),Object.keys(t).forEach(function(e){delete t[e].type}),t}function buildRbLookups(e,a,t){void 0===t&&(t=[]),e.forEach(function(e){var t,r="",o="",n="",i=toTitleCase(e.lookup.replace(/\_/g," "))+" ("+toTitleCase(e.local_key.replace("id_","").replace(/\_/g," ").replace(/\.\$\./g," -> ").replace(/\./g," -> "))+") (Lookup)",i=(e.local_key.match(/\./)?(t=e.local_key.replace(/\.\$/g,""),o=(n=e.local_key.replace(/^(.+\.).*$/,"$1")).replace(/\.$/,"")):t=e.local_key,n=n+i,a[e.local_key]?a[e.local_key].type!==String&&(r+="--local_key: '"+e.local_key+"' MUST be a String! "):r+="--local_key: '"+e.local_key+"' MUST be a valid schema path! ",{lookup_collection:e.lookup,lookup_collection_alias:i,local_key:t,field_path:o,lookup_as:n,lookup_key:"_id",type:"Object"});a[n]=i,r&&throwErr(r,e,i,n)});for(var r=0;r<t.length;r++)a[t[r]]={},a[t[r]].default_checked=!0,Object.assign(a[t[r]],a.tree[t[r]]);return a}function throwErr(e,t,r,o){void 0===o&&(o=""),console.log("------- ERROR thrown by rbLookups: "),console.log(e),console.log("---item: "),console.log(t),console.log("---Attempted to create rbSchema['"+o+"']: "),console.log(r),process.exit(1)}function roundPrecision(e,t){void 0===t&&(t=0);e=e.toString(),e.includes(".")&&("0"===e[0]&&(t+=1),t-=e.indexOf(".")),t=Math.pow(10,t);return Math.round(parseFloat(e)*t)/t}function round(e,t){void 0===t&&(t=0);t=Math.pow(10,t);return Math.round(e*t+1e-6)/t}function floorPrecision(e,t){void 0===t&&(t=0);e=e.toString(),e.includes(".")&&("0"===e[0]&&(t+=1),t-=e.indexOf(".")),t=Math.pow(10,t);return Math.floor(parseFloat(e)*t)/t}function deepCopy(e){return clone(e)}function dateReviver(e,t){if("string"==typeof t){var r=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(t);if(r)return new Date(Date.UTC(+r[1],+r[2]-1,+r[3],+r[4],+r[5],+r[6].split(".")[0],+r[6].split(".")[1]))}return t}function getMongoUpdates(e,t,r){e.createdAt&&(t.createdAt=e.createdAt),e.updatedAt&&(t.updatedAt=e.updatedAt);e=rusDiff.diff(e,t);return e?(e.$set&&!Object.keys(e.$set).length&&delete e.$set,r&&(e.$inc={__v:1})):r&&(e={$inc:{__v:1}}),e}function getMongoMergeUpdatedDoc(e,t,r){var o=deepCopy(r),t=(o.__v=t.__v,getDeepDiff(r,t));return applyMongoUpdate(o,mergeUpdates(getDeepDiff(r,e),t)),o}function mergeUpdates(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={$set:{},$unset:{},$inc:{},$push:{},$pull:{}};return e.filter(Boolean).forEach(function(e){e.forEach(function(e){var t=e.path.join(".");switch(e.kind){case"E":handleEditedChange(r,t,e);break;case"A":handleArrayChange(r,t,e)}})}),r}function handleEditedChange(e,t,r){"number"==typeof r.rhs&&(t.includes("quantity")||t.includes("qty"))?e.$inc[t]=(e.$inc[t]||0)+r.rhs-r.lhs:e.$set[t]=r.rhs}function handleArrayChange(e,t,r){"N"===r.item.kind?(e.$push[t]=e.$push[t]||[],e.$push[t].some(function(e){return JSON.stringify(e)===JSON.stringify(r.item.rhs)})||e.$push[t].push(r.item.rhs)):"D"===r.item.kind&&(e.$pull[t]=e.$pull[t]||[],e.$pull[t].some(function(e){return JSON.stringify(e)===JSON.stringify(r.item.lhs)})||e.$pull[t].push(r.item.lhs))}function getDeepDiff(e,t){return delete e._id,delete e.__v,e.updatedAt&&delete e.updatedAt,e.createdAt&&delete e.createdAt,delete t._id,delete t.__v,t.updatedAt&&delete t.updatedAt,t.createdAt&&delete t.createdAt,deepDiff(e,t)}function applyMongoUpdate(e,t){var r=deepCopy(e);return t&&(t.$rename&&handleRename(e,t.$rename),t.$set&&handleSet(e,t.$set),t.$inc&&handleInc(e,t.$inc),t.$unset&&handleUnset(e,t.$unset),t.$pull&&handlePull(e,r,t.$pull),t.$push)&&handlePush(e,t.$push),e}function handleRename(e,t){for(var r in t){var o=t[r],n=__read(resolve(e,r),2),i=n[0],n=n[1],a=__read(resolve(e,o),2),l=a[0],a=a[1];i&&1===n.length?l&&1===a.length?(l[a[0]]=i[n[0]],delete i[n[0]]):logError(l,a,e,o):logError(i,n,e,r)}}function handleSet(e,t){for(var r in t){var o=t[r],n=__read(resolve(e,r,{force:!0}),2),i=n[0],n=n[1];i&&1===n.length?i[n[0]]=o:logError(i,n,e,r)}}function handleInc(e,t){for(var r in t){var o=t[r],n=__read(resolve(e,r,{force:!0}),2),i=n[0],n=n[1];i&&1===n.length?i[n[0]]=(i[n[0]]||0)+o:logError(i,n,e,r)}}function handleUnset(e,t){for(var r in t){var o=__read(resolve(e,r),2),n=o[0],o=o[1];n&&1===o.length?delete n[o[0]]:logError(n,o,e,r)}}function handlePull(i,a,e){var t,r,l;for(l in e){var o=e[l];try{t=void 0;for(var n=__values(o),s=n.next();!s.done;s=n.next())!function(t){var e=__read(resolve(i,l),2),r=e[0],e=e[1],o=__read(resolve(a,l),2),n=o[0],o=o[1];r&&1===e.length?r[e[0]].splice(n[o[0]].findIndex(function(e){return JSON.stringify(e)===JSON.stringify(t)}),1):logError(r,e,i,l)}(s.value)}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}}}function handlePush(e,t){var r,o,n;for(n in t){var i=t[n];try{r=void 0;for(var a=__values(i),l=a.next();!l.done;l=a.next()){var s=l.value,c=__read(resolve(e,n),2),d=c[0],p=c[1];d&&1===p.length?d[p[0]].push(s):logError(d,p,e,n)}}catch(e){r={error:e}}finally{try{l&&!l.done&&(o=a.return)&&o.call(a)}finally{if(r)throw r.error}}}}function logError(e,t,r,o){console.log("Error",e+"/"+t+" - couldn't resolve for "+JSON.stringify(r)+" "+o)}function resolve(e,t,r){void 0===r&&(r={});for(var o=arrize(t),n=[],i=(0<o.length&&n.unshift(o.pop()),e);0<o.length;){var a=o.shift();if(void 0===i[a]){if(!r.force){n.unshift(a),n=o.concat(n);break}var l="number"==typeof o[0],s=0===o.length&&"number"==typeof n[0];i[a]=l||s?[]:{}}i=i[a]}return[i,n]}function arrize(e,t){return void 0===t&&(t="."),Array.isArray(e)?e.slice():null==e||!1===e||""===e?[]:e.toString().split(t).map(function(e){return[void 0,null,!1,""].includes(e)?null:e.toString()}).filter(function(e){return null!==e})}function deepDiffDetails(e,t){var r=deepCopy(e),o=deepCopy(t),n=(0,deep_object_diff_1.detailedDiff)(r,o),i="",l=function(t){return t instanceof Date?moment(t).format("llll"):"object"==typeof t&&null!==t?(Object.keys(t).filter(function(e){return e.startsWith("_id")||e.startsWith("id_")}).forEach(function(e){delete t[e]}),JSON.stringify(t)):"string"==typeof t?'"'.concat(t,'"'):String(t)},s=function(o,n){if(null===o||null===n||"object"!=typeof o||"object"!=typeof n)return"from: ".concat(l(o)," to: ").concat(l(n));if(Array.isArray(o)||Array.isArray(n)){for(var e=Array.isArray(o)?o:[],t=Array.isArray(n)?n:[],r=[],i=Math.max(e.length,t.length),a=0;a<i;a++)e[a]&&!t[a]?r.push("Removed at index ".concat(a,": ").concat(l(e[a]))):!e[a]&&t[a]?r.push("Added at index ".concat(a,": ").concat(l(t[a]))):e[a]&&t[a]&&JSON.stringify(e[a])!==JSON.stringify(t[a])&&r.push("Changed at index ".concat(a,": {").concat(s(e[a],t[a]),"}"));return r.join(", ")}return Object.keys(__assign(__assign({},o),n)).filter(function(e){return!e.startsWith("_id")&&!e.startsWith("id_")}).map(function(e){var t=o?o[e]:void 0,r=n?n[e]:void 0;return"".concat(toTitleCase(e),": ").concat(s(t,r))}).join(", ")};return["added","deleted","updated"].forEach(function(t){var e;0<Object.keys(n[t]).length&&(e=Object.keys(n[t]).filter(function(e){return"added"===t||("deleted"===t?!n.added[e]:!n.added[e]&&!n.deleted[e])}).filter(function(e){return!e.startsWith("_id")&&!e.startsWith("id_")}).map(function(e){return"\n".concat(toTitleCase(e),": ").concat(s(r[e],o[e]))}).join(","),i+=e?"".concat(e):"")}),i}function getBinarySize(e){return e?Buffer.byteLength(e,"utf8"):0}function pad(e,t){for(var r=e+"";r.length<t;)r="0"+r;return r}function randomString(e,t){for(var r="",o=e;0<o;--o)r+=t[Math.floor(Math.random()*t.length)];return r}function toTitleCase(e){return e.replace(/\w\S*/g,function(e){return e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()})}function isObject(e){return e&&"object"==typeof e&&!Array.isArray(e)}function mergeDeep(e){for(var t,r=[],o=1;o<arguments.length;o++)r[o-1]=arguments[o];if(!r.length)return e;var n=r.shift();if(isObject(e)&&isObject(n))for(var i in n)isObject(n[i])?(e[i]||Object.assign(e,((t={})[i]={},t)),mergeDeep(e[i],n[i])):Object.assign(e,((t={})[i]=n[i],t));return mergeDeep.apply(void 0,__spreadArray([e],__read(r),!1))}exports.buildRbSchema=buildRbSchema,exports.buildRbLookups=buildRbLookups,exports.throwErr=throwErr,exports.roundPrecision=roundPrecision,exports.round=round,exports.floorPrecision=floorPrecision,exports.deepCopy=deepCopy,exports.dateReviver=dateReviver,exports.getMongoUpdates=getMongoUpdates,exports.getMongoMergeUpdatedDoc=getMongoMergeUpdatedDoc,exports.mergeUpdates=mergeUpdates,exports.getDeepDiff=getDeepDiff,exports.applyMongoUpdate=applyMongoUpdate,exports.deepDiffDetails=deepDiffDetails,exports.getBinarySize=getBinarySize,exports.pad=pad,exports.randomString=randomString,exports.toTitleCase=toTitleCase,exports.isObject=isObject,exports.mergeDeep=mergeDeep;
1
+ "use strict";var __assign=this&&this.__assign||function(){return(__assign=Object.assign||function(e){for(var t,r=1,o=arguments.length;r<o;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)},__read=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var o,n,i=r.call(e),a=[];try{for(;(void 0===t||0<t--)&&!(o=i.next()).done;)a.push(o.value)}catch(e){n={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return a},__values=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],o=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&o>=e.length?void 0:e)&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},__spreadArray=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var o,n=0,i=t.length;n<i;n++)!o&&n in t||((o=o||Array.prototype.slice.call(t,0,n))[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))},rusDiff=(Object.defineProperty(exports,"__esModule",{value:!0}),exports.mergeDeep=exports.isObject=exports.toTitleCase=exports.randomString=exports.pad=exports.getBinarySize=exports.deepDiffDetails=exports.applyMongoUpdate=exports.getDeepDiff=exports.mergeUpdates=exports.getMongoMergeUpdatedDoc=exports.getMongoUpdates=exports.dateReviver=exports.deepCopy=exports.floorPrecision=exports.round=exports.roundPrecision=exports.throwErr=exports.buildRbLookups=exports.buildRbSchema=exports.objectIdHexString=void 0,require("rus-diff")),deepDiff=require("deep-diff").diff,deep_object_diff_1=require("deep-object-diff"),clone=require("clone"),moment=require("moment-timezone"),mongodb_1=require("mongodb");function objectIdHexString(){return(new mongodb_1.ObjectId).toHexString()}function buildRbSchema(t){return Object.keys(t).forEach(function(e){t[e].type===Object?(t[e].type="Object",t[e].rbType="Object"):t[e].type===Array?(t[e].type="Array",t[e].rbType="Array"):t[e].type===String?(t[e].type="String",t[e].rbType="String"):t[e].type===Date?(t[e].type="Date",t[e].rbType="Date"):t[e].type===Number?(t[e].type="Number",t[e].rbType="Number"):t[e].type===Boolean&&(t[e].rbType="Boolean",t[e].type="Boolean")}),Object.keys(t).forEach(function(e){delete t[e].type}),t}function buildRbLookups(e,a,t){void 0===t&&(t=[]),e.forEach(function(e){var t,r="",o="",n="",i=toTitleCase(e.lookup.replace(/\_/g," "))+" ("+toTitleCase(e.local_key.replace("id_","").replace(/\_/g," ").replace(/\.\$\./g," -> ").replace(/\./g," -> "))+") (Lookup)",i=(e.local_key.match(/\./)?(t=e.local_key.replace(/\.\$/g,""),o=(n=e.local_key.replace(/^(.+\.).*$/,"$1")).replace(/\.$/,"")):t=e.local_key,n=n+i,a[e.local_key]?a[e.local_key].type!==String&&(r+="--local_key: '"+e.local_key+"' MUST be a String! "):r+="--local_key: '"+e.local_key+"' MUST be a valid schema path! ",{lookup_collection:e.lookup,lookup_collection_alias:i,local_key:t,field_path:o,lookup_as:n,lookup_key:"_id",type:"Object"});a[n]=i,r&&throwErr(r,e,i,n)});for(var r=0;r<t.length;r++)a[t[r]]={},a[t[r]].default_checked=!0,Object.assign(a[t[r]],a.tree[t[r]]);return a}function throwErr(e,t,r,o){void 0===o&&(o=""),console.log("------- ERROR thrown by rbLookups: "),console.log(e),console.log("---item: "),console.log(t),console.log("---Attempted to create rbSchema['"+o+"']: "),console.log(r),process.exit(1)}function roundPrecision(e,t){void 0===t&&(t=0);e=e.toString(),e.includes(".")&&("0"===e[0]&&(t+=1),t-=e.indexOf(".")),t=Math.pow(10,t);return Math.round(parseFloat(e)*t)/t}function round(e,t){void 0===t&&(t=0);t=Math.pow(10,t);return Math.round(e*t+1e-6)/t}function floorPrecision(e,t){void 0===t&&(t=0);e=e.toString(),e.includes(".")&&("0"===e[0]&&(t+=1),t-=e.indexOf(".")),t=Math.pow(10,t);return Math.floor(parseFloat(e)*t)/t}function deepCopy(e){return clone(e)}function dateReviver(e,t){if("string"==typeof t){var r=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(t);if(r)return new Date(Date.UTC(+r[1],+r[2]-1,+r[3],+r[4],+r[5],+r[6].split(".")[0],+r[6].split(".")[1]))}return t}function getMongoUpdates(e,t,r){e.createdAt&&(t.createdAt=e.createdAt),e.updatedAt&&(t.updatedAt=e.updatedAt);e=rusDiff.diff(e,t);return e?(e.$set&&!Object.keys(e.$set).length&&delete e.$set,r&&(e.$inc={__v:1})):r&&(e={$inc:{__v:1}}),e}function getMongoMergeUpdatedDoc(e,t,r){var o=deepCopy(r),t=(o.__v=t.__v,getDeepDiff(r,t));return applyMongoUpdate(o,mergeUpdates(getDeepDiff(r,e),t)),o}function mergeUpdates(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r={$set:{},$unset:{},$inc:{},$push:{},$pull:{}};return e.filter(Boolean).forEach(function(e){e.forEach(function(e){var t=e.path.join(".");switch(e.kind){case"E":handleEditedChange(r,t,e);break;case"A":handleArrayChange(r,t,e)}})}),r}function handleEditedChange(e,t,r){"number"==typeof r.rhs&&(t.includes("quantity")||t.includes("qty"))?e.$inc[t]=(e.$inc[t]||0)+r.rhs-r.lhs:e.$set[t]=r.rhs}function handleArrayChange(e,t,r){"N"===r.item.kind?(e.$push[t]=e.$push[t]||[],e.$push[t].some(function(e){return JSON.stringify(e)===JSON.stringify(r.item.rhs)})||e.$push[t].push(r.item.rhs)):"D"===r.item.kind&&(e.$pull[t]=e.$pull[t]||[],e.$pull[t].some(function(e){return JSON.stringify(e)===JSON.stringify(r.item.lhs)})||e.$pull[t].push(r.item.lhs))}function getDeepDiff(e,t){return delete e._id,delete e.__v,e.updatedAt&&delete e.updatedAt,e.createdAt&&delete e.createdAt,delete t._id,delete t.__v,t.updatedAt&&delete t.updatedAt,t.createdAt&&delete t.createdAt,deepDiff(e,t)}function applyMongoUpdate(e,t){var r=deepCopy(e);return t&&(t.$rename&&handleRename(e,t.$rename),t.$set&&handleSet(e,t.$set),t.$inc&&handleInc(e,t.$inc),t.$unset&&handleUnset(e,t.$unset),t.$pull&&handlePull(e,r,t.$pull),t.$push)&&handlePush(e,t.$push),e}function handleRename(e,t){for(var r in t){var o=t[r],n=__read(resolve(e,r),2),i=n[0],n=n[1],a=__read(resolve(e,o),2),l=a[0],a=a[1];i&&1===n.length?l&&1===a.length?(l[a[0]]=i[n[0]],delete i[n[0]]):logError(l,a,e,o):logError(i,n,e,r)}}function handleSet(e,t){for(var r in t){var o=t[r],n=__read(resolve(e,r,{force:!0}),2),i=n[0],n=n[1];i&&1===n.length?i[n[0]]=o:logError(i,n,e,r)}}function handleInc(e,t){for(var r in t){var o=t[r],n=__read(resolve(e,r,{force:!0}),2),i=n[0],n=n[1];i&&1===n.length?i[n[0]]=(i[n[0]]||0)+o:logError(i,n,e,r)}}function handleUnset(e,t){for(var r in t){var o=__read(resolve(e,r),2),n=o[0],o=o[1];n&&1===o.length?delete n[o[0]]:logError(n,o,e,r)}}function handlePull(i,a,e){var t,r,l;for(l in e){var o=e[l];try{t=void 0;for(var n=__values(o),s=n.next();!s.done;s=n.next())!function(t){var e=__read(resolve(i,l),2),r=e[0],e=e[1],o=__read(resolve(a,l),2),n=o[0],o=o[1];r&&1===e.length?r[e[0]].splice(n[o[0]].findIndex(function(e){return JSON.stringify(e)===JSON.stringify(t)}),1):logError(r,e,i,l)}(s.value)}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}}}function handlePush(e,t){var r,o,n;for(n in t){var i=t[n];try{r=void 0;for(var a=__values(i),l=a.next();!l.done;l=a.next()){var s=l.value,d=__read(resolve(e,n),2),c=d[0],p=d[1];c&&1===p.length?c[p[0]].push(s):logError(c,p,e,n)}}catch(e){r={error:e}}finally{try{l&&!l.done&&(o=a.return)&&o.call(a)}finally{if(r)throw r.error}}}}function logError(e,t,r,o){console.log("Error",e+"/"+t+" - couldn't resolve for "+JSON.stringify(r)+" "+o)}function resolve(e,t,r){void 0===r&&(r={});for(var o=arrize(t),n=[],i=(0<o.length&&n.unshift(o.pop()),e);0<o.length;){var a=o.shift();if(void 0===i[a]){if(!r.force){n.unshift(a),n=o.concat(n);break}var l="number"==typeof o[0],s=0===o.length&&"number"==typeof n[0];i[a]=l||s?[]:{}}i=i[a]}return[i,n]}function arrize(e,t){return void 0===t&&(t="."),Array.isArray(e)?e.slice():null==e||!1===e||""===e?[]:e.toString().split(t).map(function(e){return[void 0,null,!1,""].includes(e)?null:e.toString()}).filter(function(e){return null!==e})}function deepDiffDetails(e,t){var r=deepCopy(e),o=deepCopy(t),n=(0,deep_object_diff_1.detailedDiff)(r,o),i="",l=function(t){return t instanceof Date?moment(t).format("llll"):"object"==typeof t&&null!==t?(Object.keys(t).filter(function(e){return e.startsWith("_id")||e.startsWith("id_")}).forEach(function(e){delete t[e]}),JSON.stringify(t)):"string"==typeof t?'"'.concat(t,'"'):String(t)},s=function(o,n){if(null===o||null===n||"object"!=typeof o||"object"!=typeof n)return"from: ".concat(l(o)," to: ").concat(l(n));if(Array.isArray(o)||Array.isArray(n)){for(var e=Array.isArray(o)?o:[],t=Array.isArray(n)?n:[],r=[],i=Math.max(e.length,t.length),a=0;a<i;a++)e[a]&&!t[a]?r.push("Removed at index ".concat(a,": ").concat(l(e[a]))):!e[a]&&t[a]?r.push("Added at index ".concat(a,": ").concat(l(t[a]))):e[a]&&t[a]&&JSON.stringify(e[a])!==JSON.stringify(t[a])&&r.push("Changed at index ".concat(a,": {").concat(s(e[a],t[a]),"}"));return r.join(", ")}return Object.keys(__assign(__assign({},o),n)).filter(function(e){return!e.startsWith("_id")&&!e.startsWith("id_")}).map(function(e){var t=o?o[e]:void 0,r=n?n[e]:void 0;return"".concat(toTitleCase(e),": ").concat(s(t,r))}).join(", ")};return["added","deleted","updated"].forEach(function(t){var e;0<Object.keys(n[t]).length&&(e=Object.keys(n[t]).filter(function(e){return"added"===t||("deleted"===t?!n.added[e]:!n.added[e]&&!n.deleted[e])}).filter(function(e){return!e.startsWith("_id")&&!e.startsWith("id_")}).map(function(e){return"\n".concat(toTitleCase(e),": ").concat(s(r[e],o[e]))}).join(","),i+=e?"".concat(e):"")}),i}function getBinarySize(e){return e?Buffer.byteLength(e,"utf8"):0}function pad(e,t){for(var r=e+"";r.length<t;)r="0"+r;return r}function randomString(e,t){for(var r="",o=e;0<o;--o)r+=t[Math.floor(Math.random()*t.length)];return r}function toTitleCase(e){return e.replace(/\w\S*/g,function(e){return e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()})}function isObject(e){return e&&"object"==typeof e&&!Array.isArray(e)}function mergeDeep(e){for(var t,r=[],o=1;o<arguments.length;o++)r[o-1]=arguments[o];if(!r.length)return e;var n=r.shift();if(isObject(e)&&isObject(n))for(var i in n)isObject(n[i])?(e[i]||Object.assign(e,((t={})[i]={},t)),mergeDeep(e[i],n[i])):Object.assign(e,((t={})[i]=n[i],t));return mergeDeep.apply(void 0,__spreadArray([e],__read(r),!1))}exports.objectIdHexString=objectIdHexString,exports.buildRbSchema=buildRbSchema,exports.buildRbLookups=buildRbLookups,exports.throwErr=throwErr,exports.roundPrecision=roundPrecision,exports.round=round,exports.floorPrecision=floorPrecision,exports.deepCopy=deepCopy,exports.dateReviver=dateReviver,exports.getMongoUpdates=getMongoUpdates,exports.getMongoMergeUpdatedDoc=getMongoMergeUpdatedDoc,exports.mergeUpdates=mergeUpdates,exports.getDeepDiff=getDeepDiff,exports.applyMongoUpdate=applyMongoUpdate,exports.deepDiffDetails=deepDiffDetails,exports.getBinarySize=getBinarySize,exports.pad=pad,exports.randomString=randomString,exports.toTitleCase=toTitleCase,exports.isObject=isObject,exports.mergeDeep=mergeDeep;
2
2
  //# sourceMappingURL=common.js.map