@resolveio/server-lib 22.2.34 → 22.2.35

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 (649) hide show
  1. package/ai/assistant-core-heuristics.d.ts +11 -0
  2. package/ai/assistant-core-heuristics.js +531 -0
  3. package/ai/assistant-core-heuristics.js.map +1 -0
  4. package/client-server-app.d.ts +1 -0
  5. package/client-server-app.js +68 -0
  6. package/client-server-app.js.map +1 -0
  7. package/collections/ai-terminal-conversation.collection.d.ts +2 -0
  8. package/collections/ai-terminal-conversation.collection.js +140 -0
  9. package/collections/ai-terminal-conversation.collection.js.map +1 -0
  10. package/collections/ai-terminal-issue-report.collection.d.ts +2 -0
  11. package/collections/ai-terminal-issue-report.collection.js +148 -0
  12. package/collections/ai-terminal-issue-report.collection.js.map +1 -0
  13. package/collections/ai-terminal-message.collection.d.ts +2 -0
  14. package/collections/ai-terminal-message.collection.js +121 -0
  15. package/collections/ai-terminal-message.collection.js.map +1 -0
  16. package/collections/app-setting.collection.d.ts +3 -0
  17. package/collections/app-setting.collection.js +103 -0
  18. package/collections/app-setting.collection.js.map +1 -0
  19. package/collections/app-status.collection.d.ts +3 -0
  20. package/collections/app-status.collection.js +57 -0
  21. package/collections/app-status.collection.js.map +1 -0
  22. package/collections/communication-metric.collection.d.ts +2 -0
  23. package/collections/communication-metric.collection.js +133 -0
  24. package/collections/communication-metric.collection.js.map +1 -0
  25. package/collections/counter.collection.d.ts +3 -0
  26. package/collections/counter.collection.js +56 -0
  27. package/collections/counter.collection.js.map +1 -0
  28. package/collections/cron-job-history.collection.d.ts +3 -0
  29. package/collections/cron-job-history.collection.js +137 -0
  30. package/collections/cron-job-history.collection.js.map +1 -0
  31. package/collections/cron-job.collection.d.ts +3 -0
  32. package/collections/cron-job.collection.js +92 -0
  33. package/collections/cron-job.collection.js.map +1 -0
  34. package/collections/customer-notification.collection.d.ts +3 -0
  35. package/collections/customer-notification.collection.js +130 -0
  36. package/collections/customer-notification.collection.js.map +1 -0
  37. package/collections/customer-portal-password.collection.d.ts +3 -0
  38. package/collections/customer-portal-password.collection.js +75 -0
  39. package/collections/customer-portal-password.collection.js.map +1 -0
  40. package/collections/email-history.collection.d.ts +3 -0
  41. package/collections/email-history.collection.js +121 -0
  42. package/collections/email-history.collection.js.map +1 -0
  43. package/collections/email-verified.collection.d.ts +3 -0
  44. package/collections/email-verified.collection.js +61 -0
  45. package/collections/email-verified.collection.js.map +1 -0
  46. package/collections/file.collection.d.ts +3 -0
  47. package/collections/file.collection.js +74 -0
  48. package/collections/file.collection.js.map +1 -0
  49. package/collections/flag-update.collection.d.ts +3 -0
  50. package/collections/flag-update.collection.js +57 -0
  51. package/collections/flag-update.collection.js.map +1 -0
  52. package/collections/flag.collection.d.ts +3 -0
  53. package/collections/flag.collection.js +57 -0
  54. package/collections/flag.collection.js.map +1 -0
  55. package/collections/log-method-latency.collection.d.ts +3 -0
  56. package/collections/log-method-latency.collection.js +77 -0
  57. package/collections/log-method-latency.collection.js.map +1 -0
  58. package/collections/log-subscription.collection.d.ts +3 -0
  59. package/collections/log-subscription.collection.js +80 -0
  60. package/collections/log-subscription.collection.js.map +1 -0
  61. package/collections/log.collection.d.ts +3 -0
  62. package/collections/log.collection.js +93 -0
  63. package/collections/log.collection.js.map +1 -0
  64. package/collections/logged-in-users.collection.d.ts +3 -0
  65. package/collections/logged-in-users.collection.js +67 -0
  66. package/collections/logged-in-users.collection.js.map +1 -0
  67. package/collections/monitor-cpu.collection.d.ts +3 -0
  68. package/collections/monitor-cpu.collection.js +65 -0
  69. package/collections/monitor-cpu.collection.js.map +1 -0
  70. package/collections/monitor-function.collection.d.ts +3 -0
  71. package/collections/monitor-function.collection.js +74 -0
  72. package/collections/monitor-function.collection.js.map +1 -0
  73. package/collections/monitor-memory.collection.d.ts +3 -0
  74. package/collections/monitor-memory.collection.js +77 -0
  75. package/collections/monitor-memory.collection.js.map +1 -0
  76. package/collections/monitor-mongo.collection.d.ts +3 -0
  77. package/collections/monitor-mongo.collection.js +71 -0
  78. package/collections/monitor-mongo.collection.js.map +1 -0
  79. package/collections/notification.collection.d.ts +3 -0
  80. package/collections/notification.collection.js +57 -0
  81. package/collections/notification.collection.js.map +1 -0
  82. package/collections/openai-usage-ledger.collection.d.ts +2 -0
  83. package/collections/openai-usage-ledger.collection.js +124 -0
  84. package/collections/openai-usage-ledger.collection.js.map +1 -0
  85. package/collections/report-builder-dashboard-builder.collection.d.ts +3 -0
  86. package/collections/report-builder-dashboard-builder.collection.js +109 -0
  87. package/collections/report-builder-dashboard-builder.collection.js.map +1 -0
  88. package/collections/report-builder-library.collection.d.ts +3 -0
  89. package/collections/report-builder-library.collection.js +87 -0
  90. package/collections/report-builder-library.collection.js.map +1 -0
  91. package/collections/report-builder-report.collection.d.ts +4 -0
  92. package/collections/report-builder-report.collection.js +180 -0
  93. package/collections/report-builder-report.collection.js.map +1 -0
  94. package/collections/user-group.collection.d.ts +4 -0
  95. package/collections/user-group.collection.js +89 -0
  96. package/collections/user-group.collection.js.map +1 -0
  97. package/collections/user-guide.collection.d.ts +3 -0
  98. package/collections/user-guide.collection.js +57 -0
  99. package/collections/user-guide.collection.js.map +1 -0
  100. package/collections/user.collection.d.ts +4 -0
  101. package/collections/user.collection.js +180 -0
  102. package/collections/user.collection.js.map +1 -0
  103. package/cron/cron.d.ts +14 -0
  104. package/cron/cron.js +216 -0
  105. package/cron/cron.js.map +1 -0
  106. package/fixtures/cron-jobs.d.ts +1 -0
  107. package/fixtures/cron-jobs.js +150 -0
  108. package/fixtures/cron-jobs.js.map +1 -0
  109. package/fixtures/init.d.ts +1 -0
  110. package/fixtures/init.js +91 -0
  111. package/fixtures/init.js.map +1 -0
  112. package/http/auth.d.ts +2 -0
  113. package/http/auth.js +903 -0
  114. package/http/auth.js.map +1 -0
  115. package/http/health.d.ts +1 -0
  116. package/http/health.js +11 -0
  117. package/http/health.js.map +1 -0
  118. package/http/home.d.ts +1 -0
  119. package/http/home.js +134 -0
  120. package/http/home.js.map +1 -0
  121. package/http/slow-query-publication.d.ts +2 -0
  122. package/http/slow-query-publication.js +99 -0
  123. package/http/slow-query-publication.js.map +1 -0
  124. package/index.d.ts +1 -0
  125. package/index.js +19 -0
  126. package/index.js.map +1 -0
  127. package/managers/communication-metric.manager.d.ts +16 -0
  128. package/managers/communication-metric.manager.js +134 -0
  129. package/managers/communication-metric.manager.js.map +1 -0
  130. package/managers/cron.manager.d.ts +20 -0
  131. package/managers/cron.manager.js +534 -0
  132. package/managers/cron.manager.js.map +1 -0
  133. package/managers/customer-notification-content.manager.d.ts +55 -0
  134. package/managers/customer-notification-content.manager.js +158 -0
  135. package/managers/customer-notification-content.manager.js.map +1 -0
  136. package/managers/diagnostic-manager-bootstrap.d.ts +9 -0
  137. package/managers/diagnostic-manager-bootstrap.js +260 -0
  138. package/managers/diagnostic-manager-bootstrap.js.map +1 -0
  139. package/managers/error-auto-fix.manager.d.ts +149 -0
  140. package/managers/error-auto-fix.manager.js +3064 -0
  141. package/managers/error-auto-fix.manager.js.map +1 -0
  142. package/managers/local-log.manager.d.ts +18 -0
  143. package/managers/local-log.manager.js +88 -0
  144. package/managers/local-log.manager.js.map +1 -0
  145. package/managers/method.manager.d.ts +77 -0
  146. package/managers/method.manager.js +1701 -0
  147. package/managers/method.manager.js.map +1 -0
  148. package/managers/mongo.manager.d.ts +222 -0
  149. package/managers/mongo.manager.js +4984 -0
  150. package/managers/mongo.manager.js.map +1 -0
  151. package/managers/monitor.manager.d.ts +69 -0
  152. package/managers/monitor.manager.js +534 -0
  153. package/managers/monitor.manager.js.map +1 -0
  154. package/managers/openai-usage-ledger.manager.d.ts +15 -0
  155. package/managers/openai-usage-ledger.manager.js +144 -0
  156. package/managers/openai-usage-ledger.manager.js.map +1 -0
  157. package/managers/slow-query-verifier.manager.d.ts +144 -0
  158. package/managers/slow-query-verifier.manager.js +3857 -0
  159. package/managers/slow-query-verifier.manager.js.map +1 -0
  160. package/managers/slow-query.manager.d.ts +28 -0
  161. package/managers/slow-query.manager.js +468 -0
  162. package/managers/slow-query.manager.js.map +1 -0
  163. package/managers/subscription.manager.d.ts +169 -0
  164. package/managers/subscription.manager.js +3422 -0
  165. package/managers/subscription.manager.js.map +1 -0
  166. package/managers/websocket.manager.d.ts +73 -0
  167. package/managers/websocket.manager.js +673 -0
  168. package/managers/websocket.manager.js.map +1 -0
  169. package/managers/worker-dispatcher.manager.d.ts +117 -0
  170. package/managers/worker-dispatcher.manager.js +1210 -0
  171. package/managers/worker-dispatcher.manager.js.map +1 -0
  172. package/managers/worker-server.manager.d.ts +16 -0
  173. package/managers/worker-server.manager.js +530 -0
  174. package/managers/worker-server.manager.js.map +1 -0
  175. package/methods/accounts.d.ts +2 -0
  176. package/methods/accounts.js +624 -0
  177. package/methods/accounts.js.map +1 -0
  178. package/methods/ai-terminal.d.ts +304 -0
  179. package/methods/ai-terminal.js +25096 -0
  180. package/methods/ai-terminal.js.map +1 -0
  181. package/methods/app-settings.d.ts +2 -0
  182. package/methods/app-settings.js +169 -0
  183. package/methods/app-settings.js.map +1 -0
  184. package/methods/aws.d.ts +2 -0
  185. package/methods/aws.js +874 -0
  186. package/methods/aws.js.map +1 -0
  187. package/methods/collections.d.ts +2 -0
  188. package/methods/collections.js +626 -0
  189. package/methods/collections.js.map +1 -0
  190. package/methods/counters.d.ts +2 -0
  191. package/methods/counters.js +111 -0
  192. package/methods/counters.js.map +1 -0
  193. package/methods/cron-jobs.d.ts +2 -0
  194. package/methods/cron-jobs.js +2471 -0
  195. package/methods/cron-jobs.js.map +1 -0
  196. package/methods/customer-notifications.d.ts +2 -0
  197. package/methods/customer-notifications.js +528 -0
  198. package/methods/customer-notifications.js.map +1 -0
  199. package/methods/diagnostics.d.ts +2 -0
  200. package/methods/diagnostics.js +514 -0
  201. package/methods/diagnostics.js.map +1 -0
  202. package/methods/flag-updates.d.ts +2 -0
  203. package/methods/flag-updates.js +8 -0
  204. package/methods/flag-updates.js.map +1 -0
  205. package/methods/flags.d.ts +2 -0
  206. package/methods/flags.js +8 -0
  207. package/methods/flags.js.map +1 -0
  208. package/methods/logs.d.ts +2 -0
  209. package/methods/logs.js +750 -0
  210. package/methods/logs.js.map +1 -0
  211. package/methods/mongo-explorer.d.ts +2 -0
  212. package/methods/mongo-explorer.js +1811 -0
  213. package/methods/mongo-explorer.js.map +1 -0
  214. package/methods/monitor.d.ts +2 -0
  215. package/methods/monitor.js +543 -0
  216. package/methods/monitor.js.map +1 -0
  217. package/methods/pdf.d.ts +2 -0
  218. package/methods/pdf.js +1195 -0
  219. package/methods/pdf.js.map +1 -0
  220. package/methods/publications.d.ts +1 -0
  221. package/methods/publications.js +183 -0
  222. package/methods/publications.js.map +1 -0
  223. package/methods/report-builder.d.ts +2 -0
  224. package/methods/report-builder.js +3099 -0
  225. package/methods/report-builder.js.map +1 -0
  226. package/methods/support.d.ts +2 -0
  227. package/methods/support.js +313 -0
  228. package/methods/support.js.map +1 -0
  229. package/models/ai-terminal-conversation.model.d.ts +17 -0
  230. package/models/ai-terminal-conversation.model.js +4 -0
  231. package/models/ai-terminal-conversation.model.js.map +1 -0
  232. package/models/ai-terminal-issue-report.model.d.ts +19 -0
  233. package/models/ai-terminal-issue-report.model.js +4 -0
  234. package/models/ai-terminal-issue-report.model.js.map +1 -0
  235. package/models/ai-terminal-message.model.d.ts +22 -0
  236. package/models/ai-terminal-message.model.js +4 -0
  237. package/models/ai-terminal-message.model.js.map +1 -0
  238. package/models/app-setting.model.d.ts +16 -0
  239. package/models/app-setting.model.js +4 -0
  240. package/models/app-setting.model.js.map +1 -0
  241. package/{src/models/app-status.model.ts → models/app-status.model.d.ts} +2 -3
  242. package/models/app-status.model.js +4 -0
  243. package/models/app-status.model.js.map +1 -0
  244. package/{src/models/billing-logged-in-users.model.ts → models/billing-logged-in-users.model.d.ts} +4 -5
  245. package/models/billing-logged-in-users.model.js +4 -0
  246. package/models/billing-logged-in-users.model.js.map +1 -0
  247. package/models/collection-document.model.d.ts +21 -0
  248. package/models/collection-document.model.js +4 -0
  249. package/models/collection-document.model.js.map +1 -0
  250. package/models/communication-metric.model.d.ts +20 -0
  251. package/models/communication-metric.model.js +4 -0
  252. package/models/communication-metric.model.js.map +1 -0
  253. package/{src/models/counter.model.ts → models/counter.model.d.ts} +3 -4
  254. package/models/counter.model.js +4 -0
  255. package/models/counter.model.js.map +1 -0
  256. package/models/cron-job-history.model.d.ts +15 -0
  257. package/models/cron-job-history.model.js +4 -0
  258. package/models/cron-job-history.model.js.map +1 -0
  259. package/models/cron-job.model.d.ts +14 -0
  260. package/models/cron-job.model.js +4 -0
  261. package/models/cron-job.model.js.map +1 -0
  262. package/models/customer-notification.model.d.ts +26 -0
  263. package/models/customer-notification.model.js +4 -0
  264. package/models/customer-notification.model.js.map +1 -0
  265. package/models/customer-portal-password.model.d.ts +11 -0
  266. package/models/customer-portal-password.model.js +4 -0
  267. package/models/customer-portal-password.model.js.map +1 -0
  268. package/models/dialog.model.d.ts +23 -0
  269. package/models/dialog.model.js +4 -0
  270. package/models/dialog.model.js.map +1 -0
  271. package/models/email-history.model.d.ts +30 -0
  272. package/{src/models/email-history.model.ts → models/email-history.model.js} +4 -34
  273. package/models/email-history.model.js.map +1 -0
  274. package/{src/models/email-verified.model.ts → models/email-verified.model.d.ts} +5 -6
  275. package/models/email-verified.model.js +4 -0
  276. package/models/email-verified.model.js.map +1 -0
  277. package/{src/models/file.model.ts → models/file.model.d.ts} +7 -8
  278. package/models/file.model.js +4 -0
  279. package/models/file.model.js.map +1 -0
  280. package/{src/models/flag-update.model.ts → models/flag-update.model.d.ts} +3 -4
  281. package/models/flag-update.model.js +4 -0
  282. package/models/flag-update.model.js.map +1 -0
  283. package/{src/models/flag.model.ts → models/flag.model.d.ts} +3 -4
  284. package/models/flag.model.js +4 -0
  285. package/models/flag.model.js.map +1 -0
  286. package/models/log-method-latency.model.d.ts +10 -0
  287. package/models/log-method-latency.model.js +4 -0
  288. package/models/log-method-latency.model.js.map +1 -0
  289. package/{src/models/log-subscription.model.ts → models/log-subscription.model.d.ts} +9 -11
  290. package/models/log-subscription.model.js +4 -0
  291. package/models/log-subscription.model.js.map +1 -0
  292. package/models/log.model.d.ts +17 -0
  293. package/models/log.model.js +4 -0
  294. package/models/log.model.js.map +1 -0
  295. package/{src/models/logged-in-users.model.ts → models/logged-in-users.model.d.ts} +5 -6
  296. package/models/logged-in-users.model.js +4 -0
  297. package/models/logged-in-users.model.js.map +1 -0
  298. package/{src/models/method-response.model.ts → models/method-response.model.d.ts} +6 -7
  299. package/models/method-response.model.js +4 -0
  300. package/models/method-response.model.js.map +1 -0
  301. package/models/method.model.d.ts +24 -0
  302. package/models/method.model.js +4 -0
  303. package/models/method.model.js.map +1 -0
  304. package/{src/models/monitor-cpu.model.ts → models/monitor-cpu.model.d.ts} +7 -9
  305. package/models/monitor-cpu.model.js +4 -0
  306. package/models/monitor-cpu.model.js.map +1 -0
  307. package/models/monitor-function.model.d.ts +14 -0
  308. package/models/monitor-function.model.js +4 -0
  309. package/models/monitor-function.model.js.map +1 -0
  310. package/models/monitor-memory.model.d.ts +15 -0
  311. package/models/monitor-memory.model.js +4 -0
  312. package/models/monitor-memory.model.js.map +1 -0
  313. package/models/monitor-mongo.model.d.ts +13 -0
  314. package/models/monitor-mongo.model.js +4 -0
  315. package/models/monitor-mongo.model.js.map +1 -0
  316. package/{src/models/notification.model.ts → models/notification.model.d.ts} +4 -6
  317. package/models/notification.model.js +4 -0
  318. package/models/notification.model.js.map +1 -0
  319. package/models/openai-usage-ledger.model.d.ts +15 -0
  320. package/models/openai-usage-ledger.model.js +4 -0
  321. package/models/openai-usage-ledger.model.js.map +1 -0
  322. package/models/pagination.model.d.ts +11 -0
  323. package/models/pagination.model.js +28 -0
  324. package/models/pagination.model.js.map +1 -0
  325. package/models/permission.model.d.ts +12 -0
  326. package/models/permission.model.js +4 -0
  327. package/models/permission.model.js.map +1 -0
  328. package/models/report-builder-dashboard-builder.model.d.ts +25 -0
  329. package/models/report-builder-dashboard-builder.model.js +4 -0
  330. package/models/report-builder-dashboard-builder.model.js.map +1 -0
  331. package/models/report-builder-library.model.d.ts +17 -0
  332. package/models/report-builder-library.model.js +4 -0
  333. package/models/report-builder-library.model.js.map +1 -0
  334. package/models/report-builder-report.model.d.ts +120 -0
  335. package/models/report-builder-report.model.js +4 -0
  336. package/models/report-builder-report.model.js.map +1 -0
  337. package/models/report-builder.model.d.ts +61 -0
  338. package/models/report-builder.model.js +4 -0
  339. package/models/report-builder.model.js.map +1 -0
  340. package/models/select-data-label.model.d.ts +9 -0
  341. package/models/select-data-label.model.js +4 -0
  342. package/models/select-data-label.model.js.map +1 -0
  343. package/models/server-message.model.d.ts +32 -0
  344. package/models/server-message.model.js +4 -0
  345. package/models/server-message.model.js.map +1 -0
  346. package/models/slow-query-report.model.d.ts +23 -0
  347. package/models/slow-query-report.model.js +4 -0
  348. package/models/slow-query-report.model.js.map +1 -0
  349. package/models/subscription.model.d.ts +31 -0
  350. package/models/subscription.model.js +4 -0
  351. package/models/subscription.model.js.map +1 -0
  352. package/models/support-ticket.model.d.ts +86 -0
  353. package/models/support-ticket.model.js +4 -0
  354. package/models/support-ticket.model.js.map +1 -0
  355. package/models/user-group.model.d.ts +20 -0
  356. package/models/user-group.model.js +4 -0
  357. package/models/user-group.model.js.map +1 -0
  358. package/{src/models/user-guide.model.ts → models/user-guide.model.d.ts} +4 -5
  359. package/models/user-guide.model.js +4 -0
  360. package/models/user-guide.model.js.map +1 -0
  361. package/models/user.model.d.ts +84 -0
  362. package/models/user.model.js +4 -0
  363. package/models/user.model.js.map +1 -0
  364. package/package.json +1 -1
  365. package/private/images/ResolveIO.png +0 -0
  366. package/public_api.js +107 -0
  367. package/public_api.js.map +1 -0
  368. package/publications/ai-terminal.d.ts +1 -0
  369. package/publications/ai-terminal.js +122 -0
  370. package/publications/ai-terminal.js.map +1 -0
  371. package/publications/app-settings.d.ts +2 -0
  372. package/publications/app-settings.js +28 -0
  373. package/publications/app-settings.js.map +1 -0
  374. package/publications/app-status.d.ts +2 -0
  375. package/publications/app-status.js +16 -0
  376. package/publications/app-status.js.map +1 -0
  377. package/publications/cron-jobs.d.ts +2 -0
  378. package/publications/cron-jobs.js +32 -0
  379. package/publications/cron-jobs.js.map +1 -0
  380. package/publications/customer-notifications.d.ts +2 -0
  381. package/publications/customer-notifications.js +161 -0
  382. package/publications/customer-notifications.js.map +1 -0
  383. package/publications/files.d.ts +2 -0
  384. package/publications/files.js +36 -0
  385. package/publications/files.js.map +1 -0
  386. package/publications/flags-update.d.ts +2 -0
  387. package/publications/flags-update.js +22 -0
  388. package/publications/flags-update.js.map +1 -0
  389. package/publications/flags.d.ts +2 -0
  390. package/publications/flags.js +22 -0
  391. package/publications/flags.js.map +1 -0
  392. package/publications/logs.d.ts +2 -0
  393. package/publications/logs.js +164 -0
  394. package/publications/logs.js.map +1 -0
  395. package/publications/notifications.d.ts +2 -0
  396. package/publications/notifications.js +16 -0
  397. package/publications/notifications.js.map +1 -0
  398. package/publications/report-builder-dashboard-builders.d.ts +2 -0
  399. package/publications/report-builder-dashboard-builders.js +42 -0
  400. package/publications/report-builder-dashboard-builders.js.map +1 -0
  401. package/publications/report-builder-libraries.d.ts +2 -0
  402. package/publications/report-builder-libraries.js +90 -0
  403. package/publications/report-builder-libraries.js.map +1 -0
  404. package/publications/report-builder-reports.d.ts +2 -0
  405. package/publications/report-builder-reports.js +50 -0
  406. package/publications/report-builder-reports.js.map +1 -0
  407. package/publications/super-admin.d.ts +2 -0
  408. package/publications/super-admin.js +16 -0
  409. package/publications/super-admin.js.map +1 -0
  410. package/publications/user-groups.d.ts +1 -0
  411. package/publications/user-groups.js +16 -0
  412. package/publications/user-groups.js.map +1 -0
  413. package/publications/user-guides.d.ts +1 -0
  414. package/publications/user-guides.js +16 -0
  415. package/publications/user-guides.js.map +1 -0
  416. package/resolveio-server-app.d.ts +70 -0
  417. package/resolveio-server-app.js +801 -0
  418. package/resolveio-server-app.js.map +1 -0
  419. package/server-app.d.ts +167 -0
  420. package/server-app.js +2784 -0
  421. package/server-app.js.map +1 -0
  422. package/services/codex-client.d.ts +119 -0
  423. package/services/codex-client.js +1470 -0
  424. package/services/codex-client.js.map +1 -0
  425. package/services/openai-client.d.ts +46 -0
  426. package/services/openai-client.js +318 -0
  427. package/services/openai-client.js.map +1 -0
  428. package/types/error-report.d.ts +25 -0
  429. package/types/error-report.js +4 -0
  430. package/types/error-report.js.map +1 -0
  431. package/types/slow-query-report.d.ts +27 -0
  432. package/types/slow-query-report.js +6 -0
  433. package/types/slow-query-report.js.map +1 -0
  434. package/util/common.d.ts +31 -0
  435. package/util/common.js +683 -0
  436. package/util/common.js.map +1 -0
  437. package/util/customer-portal-password.d.ts +13 -0
  438. package/util/customer-portal-password.js +209 -0
  439. package/util/customer-portal-password.js.map +1 -0
  440. package/util/error-reporter.d.ts +52 -0
  441. package/util/error-reporter.js +326 -0
  442. package/util/error-reporter.js.map +1 -0
  443. package/util/error-tracking.d.ts +13 -0
  444. package/util/error-tracking.js +120 -0
  445. package/util/error-tracking.js.map +1 -0
  446. package/util/report-builder-unwinds.d.ts +15 -0
  447. package/util/report-builder-unwinds.js +156 -0
  448. package/util/report-builder-unwinds.js.map +1 -0
  449. package/util/schema-report-builder.d.ts +6 -0
  450. package/util/schema-report-builder.js +481 -0
  451. package/util/schema-report-builder.js.map +1 -0
  452. package/util/slow-query-reporter.d.ts +28 -0
  453. package/util/slow-query-reporter.js +226 -0
  454. package/util/slow-query-reporter.js.map +1 -0
  455. package/util/subscription-dependency-context.d.ts +34 -0
  456. package/util/subscription-dependency-context.js +1283 -0
  457. package/util/subscription-dependency-context.js.map +1 -0
  458. package/util/tokenizer.d.ts +5 -0
  459. package/util/tokenizer.js +41 -0
  460. package/util/tokenizer.js.map +1 -0
  461. package/workers/codex-runner.worker.d.ts +1 -0
  462. package/workers/codex-runner.worker.js +192 -0
  463. package/workers/codex-runner.worker.js.map +1 -0
  464. package/.github/workflows/ai-assistant-nightly-eval.yml +0 -224
  465. package/.github/workflows/ai-assistant-pr-guardrails.yml +0 -60
  466. package/.nodemon.json +0 -5
  467. package/.vscode/settings.json +0 -21
  468. package/AGENTS.md +0 -179
  469. package/README.md +0 -22
  470. package/build_package.sh +0 -5
  471. package/compileDTS.pl +0 -64
  472. package/docs/ai-assistant-nightly-eval.md +0 -65
  473. package/docs/ai-assistant-preflight-checklist.md +0 -23
  474. package/docs/ai-assistant-report-builder-bridge-playbook.md +0 -115
  475. package/eslint-plugin-custom/index.js +0 -7
  476. package/eslint-plugin-custom/rules/no-filter-zero-index.js +0 -44
  477. package/eslint.config.js +0 -103
  478. package/gulpfile.js +0 -216
  479. package/methodAndPublicationListGenerator.py +0 -319
  480. package/mongodbensurers.js +0 -2
  481. package/mongostop.js +0 -3
  482. package/settings.development.json +0 -25
  483. package/settings.development.redacted.json +0 -25
  484. package/src/.env +0 -12
  485. package/src/ai/assistant-core-heuristics.ts +0 -577
  486. package/src/client-server-app.ts +0 -12
  487. package/src/collections/ai-terminal-conversation.collection.ts +0 -91
  488. package/src/collections/ai-terminal-issue-report.collection.ts +0 -99
  489. package/src/collections/ai-terminal-message.collection.ts +0 -77
  490. package/src/collections/app-setting.collection.ts +0 -104
  491. package/src/collections/app-status.collection.ts +0 -58
  492. package/src/collections/communication-metric.collection.ts +0 -84
  493. package/src/collections/counter.collection.ts +0 -56
  494. package/src/collections/cron-job-history.collection.ts +0 -94
  495. package/src/collections/cron-job.collection.ts +0 -92
  496. package/src/collections/customer-notification.collection.ts +0 -131
  497. package/src/collections/customer-portal-password.collection.ts +0 -76
  498. package/src/collections/email-history.collection.ts +0 -121
  499. package/src/collections/email-verified.collection.ts +0 -61
  500. package/src/collections/file.collection.ts +0 -74
  501. package/src/collections/flag-update.collection.ts +0 -57
  502. package/src/collections/flag.collection.ts +0 -57
  503. package/src/collections/log-method-latency.collection.ts +0 -77
  504. package/src/collections/log-subscription.collection.ts +0 -80
  505. package/src/collections/log.collection.ts +0 -93
  506. package/src/collections/logged-in-users.collection.ts +0 -67
  507. package/src/collections/monitor-cpu.collection.ts +0 -65
  508. package/src/collections/monitor-function.collection.ts +0 -74
  509. package/src/collections/monitor-memory.collection.ts +0 -77
  510. package/src/collections/monitor-mongo.collection.ts +0 -71
  511. package/src/collections/notification.collection.ts +0 -57
  512. package/src/collections/openai-usage-ledger.collection.ts +0 -77
  513. package/src/collections/report-builder-dashboard-builder.collection.ts +0 -109
  514. package/src/collections/report-builder-library.collection.ts +0 -89
  515. package/src/collections/report-builder-report.collection.ts +0 -180
  516. package/src/collections/user-group.collection.ts +0 -89
  517. package/src/collections/user-guide.collection.ts +0 -57
  518. package/src/collections/user.collection.ts +0 -181
  519. package/src/cron/cron.ts +0 -117
  520. package/src/fixtures/cron-jobs.ts +0 -95
  521. package/src/fixtures/init.ts +0 -35
  522. package/src/http/auth.ts +0 -764
  523. package/src/http/health.ts +0 -7
  524. package/src/http/home.ts +0 -90
  525. package/src/http/slow-query-publication.ts +0 -49
  526. package/src/index.ts +0 -1
  527. package/src/managers/communication-metric.manager.ts +0 -82
  528. package/src/managers/cron.manager.ts +0 -333
  529. package/src/managers/customer-notification-content.manager.ts +0 -236
  530. package/src/managers/diagnostic-manager-bootstrap.ts +0 -165
  531. package/src/managers/error-auto-fix.manager.ts +0 -2767
  532. package/src/managers/local-log.manager.ts +0 -113
  533. package/src/managers/method.manager.ts +0 -1557
  534. package/src/managers/mongo.manager.ts +0 -4566
  535. package/src/managers/monitor.manager.ts +0 -489
  536. package/src/managers/openai-usage-ledger.manager.ts +0 -116
  537. package/src/managers/slow-query-verifier.manager.ts +0 -3590
  538. package/src/managers/slow-query.manager.ts +0 -519
  539. package/src/managers/subscription.manager.ts +0 -3120
  540. package/src/managers/websocket.manager.ts +0 -746
  541. package/src/managers/worker-dispatcher.manager.ts +0 -1318
  542. package/src/managers/worker-server.manager.ts +0 -468
  543. package/src/methods/accounts.ts +0 -532
  544. package/src/methods/ai-terminal.ts +0 -25505
  545. package/src/methods/app-settings.ts +0 -114
  546. package/src/methods/aws.ts +0 -646
  547. package/src/methods/collections.ts +0 -544
  548. package/src/methods/counters.ts +0 -67
  549. package/src/methods/cron-jobs.ts +0 -2610
  550. package/src/methods/customer-notifications.ts +0 -458
  551. package/src/methods/diagnostics.ts +0 -447
  552. package/src/methods/flag-updates.ts +0 -7
  553. package/src/methods/flags.ts +0 -7
  554. package/src/methods/logs.ts +0 -656
  555. package/src/methods/mongo-explorer.ts +0 -1883
  556. package/src/methods/monitor.ts +0 -540
  557. package/src/methods/pdf.ts +0 -1210
  558. package/src/methods/publications.ts +0 -128
  559. package/src/methods/report-builder.ts +0 -3305
  560. package/src/methods/support.ts +0 -210
  561. package/src/models/ai-terminal-conversation.model.ts +0 -19
  562. package/src/models/ai-terminal-issue-report.model.ts +0 -21
  563. package/src/models/ai-terminal-message.model.ts +0 -24
  564. package/src/models/app-setting.model.ts +0 -17
  565. package/src/models/collection-document.model.ts +0 -24
  566. package/src/models/communication-metric.model.ts +0 -23
  567. package/src/models/cron-job-history.model.ts +0 -16
  568. package/src/models/cron-job.model.ts +0 -15
  569. package/src/models/customer-notification.model.ts +0 -28
  570. package/src/models/customer-portal-password.model.ts +0 -12
  571. package/src/models/dialog.model.ts +0 -25
  572. package/src/models/log-method-latency.model.ts +0 -11
  573. package/src/models/log.model.ts +0 -19
  574. package/src/models/method.model.ts +0 -23
  575. package/src/models/monitor-function.model.ts +0 -16
  576. package/src/models/monitor-memory.model.ts +0 -17
  577. package/src/models/monitor-mongo.model.ts +0 -15
  578. package/src/models/openai-usage-ledger.model.ts +0 -16
  579. package/src/models/pagination.model.ts +0 -35
  580. package/src/models/permission.model.ts +0 -14
  581. package/src/models/report-builder-dashboard-builder.model.ts +0 -29
  582. package/src/models/report-builder-library.model.ts +0 -20
  583. package/src/models/report-builder-report.model.ts +0 -135
  584. package/src/models/report-builder.model.ts +0 -68
  585. package/src/models/select-data-label.model.ts +0 -9
  586. package/src/models/server-message.model.ts +0 -31
  587. package/src/models/slow-query-report.model.ts +0 -23
  588. package/src/models/subscription.model.ts +0 -73
  589. package/src/models/support-ticket.model.ts +0 -96
  590. package/src/models/user-group.model.ts +0 -24
  591. package/src/models/user.model.ts +0 -96
  592. package/src/private/images/ResolveIO.png +0 -0
  593. package/src/publications/ai-terminal.ts +0 -73
  594. package/src/publications/app-settings.ts +0 -25
  595. package/src/publications/app-status.ts +0 -13
  596. package/src/publications/cron-jobs.ts +0 -29
  597. package/src/publications/customer-notifications.ts +0 -101
  598. package/src/publications/files.ts +0 -33
  599. package/src/publications/flags-update.ts +0 -19
  600. package/src/publications/flags.ts +0 -19
  601. package/src/publications/logs.ts +0 -163
  602. package/src/publications/notifications.ts +0 -13
  603. package/src/publications/report-builder-dashboard-builders.ts +0 -39
  604. package/src/publications/report-builder-libraries.ts +0 -41
  605. package/src/publications/report-builder-reports.ts +0 -47
  606. package/src/publications/super-admin.ts +0 -13
  607. package/src/publications/user-groups.ts +0 -12
  608. package/src/publications/user-guides.ts +0 -12
  609. package/src/resolveio-server-app.ts +0 -617
  610. package/src/server-app.ts +0 -2616
  611. package/src/services/codex-client.ts +0 -1117
  612. package/src/services/openai-client.ts +0 -265
  613. package/src/types/error-report.ts +0 -26
  614. package/src/types/js-tiktoken.d.ts +0 -11
  615. package/src/types/slow-query-report.ts +0 -28
  616. package/src/util/common.ts +0 -649
  617. package/src/util/customer-portal-password.ts +0 -183
  618. package/src/util/error-reporter.ts +0 -332
  619. package/src/util/error-tracking.ts +0 -79
  620. package/src/util/report-builder-unwinds.ts +0 -180
  621. package/src/util/schema-report-builder.ts +0 -448
  622. package/src/util/slow-query-reporter.ts +0 -216
  623. package/src/util/subscription-dependency-context.ts +0 -1096
  624. package/src/util/tokenizer.ts +0 -38
  625. package/src/workers/codex-runner.worker.ts +0 -142
  626. package/start_server.sh +0 -5
  627. package/tests/ai-assistant-corpus-build.ts +0 -484
  628. package/tests/ai-assistant-corpus-replay-e2e.ts +0 -773
  629. package/tests/ai-assistant-data-parity-e2e.ts +0 -2018
  630. package/tests/ai-assistant-eval-triage.ts +0 -831
  631. package/tests/ai-assistant-openai-e2e.ts +0 -1061
  632. package/tests/ai-assistant-openai-git-e2e.ts +0 -155
  633. package/tests/ai-assistant-preflight-matrix.ts +0 -215
  634. package/tests/ai-assistant-routing-eval.test.ts +0 -560
  635. package/tests/ai-assistant-snf-live-eval.ts +0 -921
  636. package/tests/ai-assistant-utils.test.ts +0 -2165
  637. package/tests/error-reporter.test.ts +0 -145
  638. package/tests/report-builder-linking.test.ts +0 -79
  639. package/tests/subscription-connect-race.test.ts +0 -157
  640. package/tests/subscription-dependency-context.test.ts +0 -324
  641. package/tests/subscription-manager-collection-tracking.test.ts +0 -86
  642. package/tests/subscription-manager-invalidation.test.ts +0 -85
  643. package/tsconfig.json +0 -34
  644. /package/{src/private → private}/email-templates/enrollment.html +0 -0
  645. /package/{src/private → private}/email-templates/forgot-password.html +0 -0
  646. /package/{src/private → private}/email-templates/support-ticket-deleted.html +0 -0
  647. /package/{src/private → private}/email-templates/support-ticket-modified.html +0 -0
  648. /package/{src/private → private}/email-templates/support-ticket.html +0 -0
  649. /package/{src/public_api.ts → public_api.d.ts} +0 -0
@@ -0,0 +1,1701 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ var __read = (this && this.__read) || function (o, n) {
50
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
51
+ if (!m) return o;
52
+ var i = m.call(o), r, ar = [], e;
53
+ try {
54
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
+ }
56
+ catch (error) { e = { error: error }; }
57
+ finally {
58
+ try {
59
+ if (r && !r.done && (m = i["return"])) m.call(i);
60
+ }
61
+ finally { if (e) throw e.error; }
62
+ }
63
+ return ar;
64
+ };
65
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
66
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
67
+ if (ar || !(i in from)) {
68
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
69
+ ar[i] = from[i];
70
+ }
71
+ }
72
+ return to.concat(ar || Array.prototype.slice.call(from));
73
+ };
74
+ var __values = (this && this.__values) || function(o) {
75
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
76
+ if (m) return m.call(o);
77
+ if (o && typeof o.length === "number") return {
78
+ next: function () {
79
+ if (o && i >= o.length) o = void 0;
80
+ return { value: o && o[i++], done: !o };
81
+ }
82
+ };
83
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
84
+ };
85
+ Object.defineProperty(exports, "__esModule", { value: true });
86
+ exports.MethodManager = exports.AWS = void 0;
87
+ var client_s3_1 = require("@aws-sdk/client-s3");
88
+ var client_sesv2_1 = require("@aws-sdk/client-sesv2");
89
+ var events_1 = require("events");
90
+ var fs = require("fs");
91
+ var nodemailer = require("nodemailer");
92
+ var path = require("path");
93
+ var promises_1 = require("timers/promises");
94
+ var email_history_collection_1 = require("../collections/email-history.collection");
95
+ var flag_collection_1 = require("../collections/flag.collection");
96
+ var log_collection_1 = require("../collections/log.collection");
97
+ var cron_jobs_1 = require("../fixtures/cron-jobs");
98
+ var init_1 = require("../fixtures/init");
99
+ var accounts_1 = require("../methods/accounts");
100
+ var app_settings_1 = require("../methods/app-settings");
101
+ var aws_1 = require("../methods/aws");
102
+ var ai_terminal_1 = require("../methods/ai-terminal");
103
+ var collections_1 = require("../methods/collections");
104
+ var customer_notifications_1 = require("../methods/customer-notifications");
105
+ var counters_1 = require("../methods/counters");
106
+ var cron_jobs_2 = require("../methods/cron-jobs");
107
+ var diagnostics_1 = require("../methods/diagnostics");
108
+ var flag_updates_1 = require("../methods/flag-updates");
109
+ var flags_1 = require("../methods/flags");
110
+ var logs_1 = require("../methods/logs");
111
+ var monitor_1 = require("../methods/monitor");
112
+ var mongo_explorer_1 = require("../methods/mongo-explorer");
113
+ var publications_1 = require("../methods/publications");
114
+ var pdf_1 = require("../methods/pdf");
115
+ var report_builder_1 = require("../methods/report-builder");
116
+ var support_1 = require("../methods/support");
117
+ var resolveio_server_app_1 = require("../resolveio-server-app");
118
+ var common_1 = require("../util/common");
119
+ var error_reporter_1 = require("../util/error-reporter");
120
+ var error_tracking_1 = require("../util/error-tracking");
121
+ var communication_metric_manager_1 = require("./communication-metric.manager");
122
+ function appendCorrelationIdToSubject(subject, correlationId) {
123
+ if (!correlationId) {
124
+ return subject;
125
+ }
126
+ var correlationTag = "[".concat(correlationId, "]");
127
+ if (subject && subject.includes(correlationTag)) {
128
+ return subject;
129
+ }
130
+ return "".concat(subject, " ").concat(correlationTag).trim();
131
+ }
132
+ function createEmailOccurrence(subject, text, html, meta) {
133
+ return {
134
+ _id: (0, common_1.objectIdHexString)(),
135
+ createdAt: new Date(),
136
+ subject: subject,
137
+ text: text,
138
+ html: html,
139
+ meta: meta
140
+ };
141
+ }
142
+ function formatGroupedEmailContent(correlationId, occurrences) {
143
+ var lines = [];
144
+ lines.push("Correlation ID: ".concat(correlationId));
145
+ occurrences.forEach(function (occurrence, index) {
146
+ var timestamp = occurrence.createdAt instanceof Date ? occurrence.createdAt.toISOString() : new Date(occurrence.createdAt).toISOString();
147
+ lines.push('');
148
+ lines.push("Occurrence #".concat(index + 1, " (").concat(timestamp, ")"));
149
+ lines.push("Subject: ".concat(occurrence.subject));
150
+ if (occurrence.text) {
151
+ lines.push(occurrence.text);
152
+ }
153
+ });
154
+ var htmlSections = occurrences.map(function (occurrence, index) {
155
+ var timestamp = occurrence.createdAt instanceof Date ? occurrence.createdAt.toISOString() : new Date(occurrence.createdAt).toISOString();
156
+ var escapedText = occurrence.text ? occurrence.text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;') : '';
157
+ return "<div><h4>Occurrence #".concat(index + 1, " (").concat(timestamp, ")</h4><p><strong>Subject:</strong> ").concat(occurrence.subject, "</p>").concat(escapedText ? "<pre>".concat(escapedText, "</pre>") : '', "</div>");
158
+ });
159
+ var html = __spreadArray([
160
+ "<p><strong>Correlation ID:</strong> ".concat(correlationId, "</p>")
161
+ ], __read(htmlSections), false).join('');
162
+ return {
163
+ text: lines.join('\n'),
164
+ html: html
165
+ };
166
+ }
167
+ function createNodeMailerSESV2Transport(sesClient) {
168
+ var _this = this;
169
+ var transport = {
170
+ name: 'resolveio-sesv2-transport',
171
+ version: '1.0.0',
172
+ send: function (mail, callback) {
173
+ var stream = mail.message.createReadStream();
174
+ var chunks = [];
175
+ var didFinish = false;
176
+ var finish = function (error, info) {
177
+ if (didFinish) {
178
+ return;
179
+ }
180
+ didFinish = true;
181
+ callback(error, info);
182
+ };
183
+ stream.on('data', function (chunk) {
184
+ var chunkData = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
185
+ chunks.push(new Uint8Array(chunkData));
186
+ });
187
+ stream.on('error', function (error) {
188
+ finish(error);
189
+ });
190
+ stream.on('end', function () { return __awaiter(_this, void 0, void 0, function () {
191
+ var rawData, rawMessageData, envelope, fromEmailAddress, toAddresses, replyToAddresses, response, error_1;
192
+ var _a, _b;
193
+ return __generator(this, function (_c) {
194
+ switch (_c.label) {
195
+ case 0:
196
+ _c.trys.push([0, 2, , 3]);
197
+ rawData = Buffer.concat(chunks);
198
+ rawMessageData = new Uint8Array(rawData);
199
+ envelope = typeof mail.message.getEnvelope === 'function' ? mail.message.getEnvelope() : (_a = mail.data) === null || _a === void 0 ? void 0 : _a.envelope;
200
+ fromEmailAddress = (envelope === null || envelope === void 0 ? void 0 : envelope.from) || undefined;
201
+ toAddresses = (envelope === null || envelope === void 0 ? void 0 : envelope.to)
202
+ ? (Array.isArray(envelope.to) ? envelope.to : [envelope.to]).filter(Boolean)
203
+ : [];
204
+ replyToAddresses = ((_b = mail.data) === null || _b === void 0 ? void 0 : _b.replyTo)
205
+ ? (Array.isArray(mail.data.replyTo) ? mail.data.replyTo : [mail.data.replyTo]).filter(Boolean)
206
+ : undefined;
207
+ return [4 /*yield*/, sesClient.send(new client_sesv2_1.SendEmailCommand({
208
+ FromEmailAddress: fromEmailAddress,
209
+ Destination: toAddresses.length ? { ToAddresses: toAddresses } : undefined,
210
+ ReplyToAddresses: replyToAddresses,
211
+ Content: {
212
+ Raw: {
213
+ Data: rawMessageData
214
+ }
215
+ }
216
+ }))];
217
+ case 1:
218
+ response = _c.sent();
219
+ finish(null, {
220
+ envelope: envelope,
221
+ messageId: response.MessageId,
222
+ response: response.MessageId
223
+ });
224
+ return [3 /*break*/, 3];
225
+ case 2:
226
+ error_1 = _c.sent();
227
+ finish(error_1);
228
+ return [3 /*break*/, 3];
229
+ case 3: return [2 /*return*/];
230
+ }
231
+ });
232
+ }); });
233
+ }
234
+ };
235
+ return nodemailer.createTransport(transport);
236
+ }
237
+ var AWS = /** @class */ (function () {
238
+ function AWS() {
239
+ this._s3 = null;
240
+ this._s3USEast1 = null;
241
+ }
242
+ AWS.prototype.create = function () {
243
+ var aws = new AWS();
244
+ aws.initialize();
245
+ return aws;
246
+ };
247
+ AWS.prototype.initialize = function () {
248
+ };
249
+ AWS.prototype.s3 = function () {
250
+ if (this._s3) {
251
+ return this._s3;
252
+ }
253
+ this._s3 = new client_s3_1.S3({
254
+ credentials: {
255
+ accessKeyId: process.env.AWS_ACCESS_KEY,
256
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
257
+ },
258
+ region: process.env.AWS_REGION,
259
+ apiVersion: '2006-03-01'
260
+ });
261
+ return this._s3;
262
+ };
263
+ AWS.prototype.s3USEast1 = function () {
264
+ if (process.env.AWS_REGION === 'us-east-1') {
265
+ return this.s3();
266
+ }
267
+ else {
268
+ if (this._s3USEast1) {
269
+ return this._s3USEast1;
270
+ }
271
+ this._s3USEast1 = new client_s3_1.S3({
272
+ credentials: {
273
+ accessKeyId: process.env.AWS_ACCESS_KEY,
274
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
275
+ },
276
+ region: 'us-east-1',
277
+ apiVersion: '2006-03-01'
278
+ });
279
+ return this._s3USEast1;
280
+ }
281
+ };
282
+ return AWS;
283
+ }());
284
+ exports.AWS = AWS;
285
+ var MethodManager = /** @class */ (function () {
286
+ function MethodManager() {
287
+ this._methods = {};
288
+ this._isWorkersEnabled = false;
289
+ this._isWorkerInstance = false;
290
+ this.emailQueue = new Set(); // Set to store pending email IDs
291
+ this.isEmailProcessing = false;
292
+ this._emailProcessingDelayMs = 5000;
293
+ this._debugcallMethodHits = 0;
294
+ this._debugCallMethodHits = 0;
295
+ this._debugCallMethodCronJobHits = 0;
296
+ this._debugSendQueueHits = 0;
297
+ this._enableDebug = false;
298
+ this._ready = false;
299
+ this._readyEmitter = new events_1.EventEmitter();
300
+ this._readyError = null;
301
+ this._localActiveCounts = new Map();
302
+ this._localWaitQueues = new Map();
303
+ this.clientDir = '';
304
+ this.serverConfig = {};
305
+ }
306
+ MethodManager.create = function (websocketManager, monitorManagerFunction, isWorkersEnabled, isWorkerInstance) {
307
+ var methodManager = new MethodManager();
308
+ methodManager.initialize(websocketManager, monitorManagerFunction, isWorkersEnabled, isWorkerInstance);
309
+ return methodManager;
310
+ };
311
+ MethodManager.prototype.initialize = function (websocketManager, monitorManagerFunction, isWorkersEnabled, isWorkerInstance) {
312
+ var _this = this;
313
+ this._websocketManager = websocketManager;
314
+ this._monitorManagerFunction = monitorManagerFunction;
315
+ this._isWorkersEnabled = isWorkersEnabled;
316
+ this._isWorkerInstance = isWorkerInstance;
317
+ this.clientDir = resolveio_server_app_1.ResolveIOServer.getClientDir();
318
+ this.serverConfig = resolveio_server_app_1.ResolveIOServer.getServerConfig();
319
+ // Fixtures
320
+ if (!process.env.IS_WORKERS_ENABLED || process.env.IS_WORKERS_ENABLED === 'false' || (process.env.IS_WORKER_INSTANCE === 'true' && process.env.WORKER_INDEX === '0')) {
321
+ if (process.env.IS_WORKERS_ENABLED === 'false' || process.env.NODE_APP_INSTANCE === '1') {
322
+ setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
323
+ return __generator(this, function (_a) {
324
+ switch (_a.label) {
325
+ case 0:
326
+ console.log(new Date(), 'Start Server Fixture');
327
+ return [4 /*yield*/, (0, init_1.loadServerInit)()];
328
+ case 1:
329
+ _a.sent();
330
+ console.log(new Date(), 'End Server Fixture');
331
+ return [2 /*return*/];
332
+ }
333
+ });
334
+ }); }, 5000);
335
+ }
336
+ }
337
+ setImmediate(function () { return __awaiter(_this, void 0, void 0, function () {
338
+ var flag, error_2;
339
+ return __generator(this, function (_a) {
340
+ switch (_a.label) {
341
+ case 0:
342
+ _a.trys.push([0, 4, , 5]);
343
+ // Methods
344
+ return [4 /*yield*/, (0, cron_jobs_1.loadServerCronJobs)()];
345
+ case 1:
346
+ // Methods
347
+ _a.sent();
348
+ (0, accounts_1.loadAccountMethods)(this);
349
+ (0, app_settings_1.loadAppSettingsMethods)(this);
350
+ (0, aws_1.loadAWSMethods)(this);
351
+ (0, ai_terminal_1.loadAiTerminalMethods)(this);
352
+ (0, collections_1.loadCollectionMethods)(this);
353
+ (0, customer_notifications_1.loadCustomerNotificationMethods)(this);
354
+ (0, counters_1.loadCounterMethods)(this);
355
+ (0, logs_1.loadLogMethods)(this);
356
+ (0, pdf_1.loadPDFMethods)(this);
357
+ (0, cron_jobs_2.loadCronJobMethods)(this);
358
+ (0, flags_1.loadFlagMethods)(this);
359
+ (0, flag_updates_1.loadFlagUpdatesMethods)(this);
360
+ (0, report_builder_1.loadReportBuilderMethods)(this);
361
+ (0, support_1.loadSupportMethods)(this);
362
+ (0, monitor_1.loadMonitorMethods)(this);
363
+ (0, mongo_explorer_1.loadMongoExplorerMethods)(this);
364
+ (0, publications_1.loadPublicationMethods)(this);
365
+ (0, diagnostics_1.loadDiagnosticMethods)(this);
366
+ return [4 /*yield*/, flag_collection_1.Flags.findOne({ type: 'Enable Debug' })];
367
+ case 2:
368
+ flag = _a.sent();
369
+ if (flag && flag.value) {
370
+ this._enableDebug = true;
371
+ }
372
+ else {
373
+ this._enableDebug = false;
374
+ }
375
+ return [4 /*yield*/, this.loadPendingEmails()];
376
+ case 3:
377
+ _a.sent();
378
+ this.markReady();
379
+ return [3 /*break*/, 5];
380
+ case 4:
381
+ error_2 = _a.sent();
382
+ console.error(new Date(), 'Method Manager init failed', error_2);
383
+ this.markReadyFailure(error_2);
384
+ return [3 /*break*/, 5];
385
+ case 5: return [2 /*return*/];
386
+ }
387
+ });
388
+ }); });
389
+ this._aws = new AWS();
390
+ var sesRegion = process.env.AWS_SES_REGION || process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || 'us-east-1';
391
+ var sesCredentials = process.env.AWS_ACCESS_KEY && process.env.AWS_SECRET_ACCESS_KEY ? {
392
+ accessKeyId: process.env.AWS_ACCESS_KEY,
393
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
394
+ sessionToken: process.env.AWS_SESSION_TOKEN
395
+ } : undefined;
396
+ this._mailerSES = createNodeMailerSESV2Transport(new client_sesv2_1.SESv2Client({
397
+ region: sesRegion,
398
+ credentials: sesCredentials
399
+ }));
400
+ if (!resolveio_server_app_1.ResolveIOServer.getSESMail()) {
401
+ this._mailerCustom = nodemailer.createTransport({
402
+ host: resolveio_server_app_1.ResolveIOServer.getServerConfig()['MAIL_HOST'], // 'smtp.office365.com', // Office 365 server
403
+ port: resolveio_server_app_1.ResolveIOServer.getServerConfig()['MAIL_PORT'], //587, // secure SMTP
404
+ secure: false, // false for TLS - as a boolean not string - but the default is false so just remove this completely
405
+ auth: {
406
+ user: resolveio_server_app_1.ResolveIOServer.getServerConfig()['MAIL_USERNAME'],
407
+ pass: resolveio_server_app_1.ResolveIOServer.getServerConfig()['MAIL_PASSWORD']
408
+ },
409
+ tls: {
410
+ ciphers: 'SSLv3'
411
+ }
412
+ });
413
+ }
414
+ setInterval(function () { return __awaiter(_this, void 0, void 0, function () {
415
+ var flag;
416
+ return __generator(this, function (_a) {
417
+ switch (_a.label) {
418
+ case 0: return [4 /*yield*/, flag_collection_1.Flags.findOne({ type: 'Enable Debug' })];
419
+ case 1:
420
+ flag = _a.sent();
421
+ if (flag && flag.value) {
422
+ this._enableDebug = true;
423
+ }
424
+ else {
425
+ this._enableDebug = false;
426
+ }
427
+ if (this._enableDebug) {
428
+ console.log(new Date(), 'Method Manager', 'Send Queue Hits', this._debugSendQueueHits);
429
+ console.log(new Date(), 'Method Manager', 'Call Method Internal Hits', this._debugcallMethodHits);
430
+ console.log(new Date(), 'Method Manager', 'Call Method Hits', this._debugCallMethodHits);
431
+ console.log(new Date(), 'Method Manager', 'Call Method Cron Hits', this._debugCallMethodCronJobHits);
432
+ }
433
+ this._debugcallMethodHits = 0;
434
+ this._debugCallMethodHits = 0;
435
+ this._debugCallMethodCronJobHits = 0;
436
+ this._debugSendQueueHits = 0;
437
+ return [2 /*return*/];
438
+ }
439
+ });
440
+ }); }, 60000);
441
+ if (!this._isWorkersEnabled || this._isWorkerInstance) {
442
+ this.setupEmailWatcher();
443
+ }
444
+ };
445
+ MethodManager.prototype.markReady = function () {
446
+ if (this._ready) {
447
+ return;
448
+ }
449
+ this._ready = true;
450
+ this._readyEmitter.emit('ready');
451
+ this._readyEmitter.removeAllListeners('ready');
452
+ this._readyEmitter.removeAllListeners('readyError');
453
+ };
454
+ MethodManager.prototype.markReadyFailure = function (error) {
455
+ if (this._ready) {
456
+ return;
457
+ }
458
+ this._readyError = error;
459
+ this._readyEmitter.emit('readyError', error);
460
+ this._readyEmitter.removeAllListeners('ready');
461
+ this._readyEmitter.removeAllListeners('readyError');
462
+ };
463
+ MethodManager.prototype.onReady = function (callback) {
464
+ var _this = this;
465
+ if (this._ready) {
466
+ callback();
467
+ return function () { };
468
+ }
469
+ if (this._readyError) {
470
+ return function () { };
471
+ }
472
+ var handleReady = function () {
473
+ callback();
474
+ };
475
+ this._readyEmitter.once('ready', handleReady);
476
+ return function () {
477
+ _this._readyEmitter.removeListener('ready', handleReady);
478
+ };
479
+ };
480
+ MethodManager.prototype.waitForReadyEvent = function () {
481
+ return __awaiter(this, void 0, void 0, function () {
482
+ return __generator(this, function (_a) {
483
+ switch (_a.label) {
484
+ case 0: return [4 /*yield*/, (0, events_1.once)(this._readyEmitter, 'ready')];
485
+ case 1:
486
+ _a.sent();
487
+ return [2 /*return*/];
488
+ }
489
+ });
490
+ });
491
+ };
492
+ MethodManager.prototype.waitForReadyError = function () {
493
+ return __awaiter(this, void 0, void 0, function () {
494
+ var _a, error;
495
+ return __generator(this, function (_b) {
496
+ switch (_b.label) {
497
+ case 0: return [4 /*yield*/, (0, events_1.once)(this._readyEmitter, 'readyError')];
498
+ case 1:
499
+ _a = __read.apply(void 0, [_b.sent(), 1]), error = _a[0];
500
+ throw error || new Error('MethodManager failed to initialize');
501
+ }
502
+ });
503
+ });
504
+ };
505
+ MethodManager.prototype.waitForReadyTimeout = function (timeoutMs) {
506
+ return __awaiter(this, void 0, void 0, function () {
507
+ return __generator(this, function (_a) {
508
+ switch (_a.label) {
509
+ case 0: return [4 /*yield*/, (0, promises_1.setTimeout)(timeoutMs)];
510
+ case 1:
511
+ _a.sent();
512
+ throw new Error('MethodManager ready timeout');
513
+ }
514
+ });
515
+ });
516
+ };
517
+ MethodManager.prototype.isReady = function () {
518
+ return this._ready;
519
+ };
520
+ MethodManager.prototype.getReadyError = function () {
521
+ return this._readyError;
522
+ };
523
+ MethodManager.prototype.waitUntilReady = function () {
524
+ return __awaiter(this, arguments, void 0, function (timeoutMs) {
525
+ if (timeoutMs === void 0) { timeoutMs = 30000; }
526
+ return __generator(this, function (_a) {
527
+ switch (_a.label) {
528
+ case 0:
529
+ if (this._ready) {
530
+ return [2 /*return*/];
531
+ }
532
+ if (this._readyError) {
533
+ throw this._readyError;
534
+ }
535
+ if (!(!timeoutMs || timeoutMs <= 0)) return [3 /*break*/, 2];
536
+ return [4 /*yield*/, Promise.race([
537
+ this.waitForReadyEvent(),
538
+ this.waitForReadyError()
539
+ ])];
540
+ case 1:
541
+ _a.sent();
542
+ return [2 /*return*/];
543
+ case 2: return [4 /*yield*/, Promise.race([
544
+ this.waitForReadyEvent(),
545
+ this.waitForReadyError(),
546
+ this.waitForReadyTimeout(timeoutMs)
547
+ ])];
548
+ case 3:
549
+ _a.sent();
550
+ return [2 /*return*/];
551
+ }
552
+ });
553
+ });
554
+ };
555
+ MethodManager.prototype.getMethod = function (methodName) {
556
+ return this._methods[methodName];
557
+ };
558
+ // Add methods to private methods object
559
+ MethodManager.prototype.methods = function (method) {
560
+ this._methods = Object.assign(this._methods, method);
561
+ };
562
+ MethodManager.prototype.reportMethodError = function (subject, correlationId, context, meta, stack) {
563
+ return __awaiter(this, void 0, void 0, function () {
564
+ var metadata;
565
+ var _a, _b;
566
+ return __generator(this, function (_c) {
567
+ switch (_c.label) {
568
+ case 0:
569
+ metadata = Object.assign({}, meta || {});
570
+ if (correlationId && !metadata.correlationId) {
571
+ metadata.correlationId = correlationId;
572
+ }
573
+ return [4 /*yield*/, error_reporter_1.ErrorReporter.report({
574
+ sourceApp: 'method-manager',
575
+ message: subject,
576
+ environment: (_a = this.serverConfig) === null || _a === void 0 ? void 0 : _a.ROOT_URL,
577
+ clientSlug: resolveio_server_app_1.ResolveIOServer.getClientName(),
578
+ clientName: (_b = this.serverConfig) === null || _b === void 0 ? void 0 : _b.CLIENT_NAME,
579
+ severity: 'error',
580
+ stack: stack,
581
+ context: context,
582
+ metadata: metadata,
583
+ correlationId: correlationId
584
+ })];
585
+ case 1:
586
+ _c.sent();
587
+ return [2 /*return*/];
588
+ }
589
+ });
590
+ });
591
+ };
592
+ MethodManager.prototype.callMethodCron = function (method) {
593
+ var methodData = [];
594
+ for (var _i = 1; _i < arguments.length; _i++) {
595
+ methodData[_i - 1] = arguments[_i];
596
+ }
597
+ return __awaiter(this, void 0, void 0, function () {
598
+ var existingCorrelationId, correlationId, execute;
599
+ var _this = this;
600
+ return __generator(this, function (_a) {
601
+ switch (_a.label) {
602
+ case 0:
603
+ this._debugCallMethodCronJobHits += 1;
604
+ existingCorrelationId = (0, error_tracking_1.getCorrelationId)();
605
+ correlationId = existingCorrelationId || (0, common_1.objectIdHexString)();
606
+ execute = function () { return __awaiter(_this, void 0, void 0, function () {
607
+ var cronMethod, valObj, valKeys, rootKeys, i, err_1, _a, normalizedError, resolvedCorrelationId, monitor, res, err_2, _b, normalizedError, resolvedCorrelationId;
608
+ var _c;
609
+ return __generator(this, function (_d) {
610
+ switch (_d.label) {
611
+ case 0:
612
+ cronMethod = this._methods[method];
613
+ if (!!cronMethod) return [3 /*break*/, 2];
614
+ console.log('No Method: ' + method);
615
+ return [4 /*yield*/, this.reportMethodError('SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], correlationId, { message: 'No Method registered for cron execution', method: method }, { context: 'callMethodCron', method: method })];
616
+ case 1:
617
+ _d.sent();
618
+ throw new Error('No Method: ' + method);
619
+ case 2:
620
+ if (!((methodData.length > 1 || methodData[0]) && !cronMethod.skipValidation)) return [3 /*break*/, 10];
621
+ if (!!cronMethod.check) return [3 /*break*/, 4];
622
+ console.error(new Date(), 'No Check Function For Cron Method ' + method);
623
+ return [4 /*yield*/, this.reportMethodError('SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], correlationId, { message: 'Missing check function for cron method', method: method }, { context: 'callMethodCron-validation', method: method })];
624
+ case 3:
625
+ _d.sent();
626
+ throw new Error('No Check Function For Cron Method ' + method);
627
+ case 4:
628
+ if (!!cronMethod.check._schema) return [3 /*break*/, 6];
629
+ console.error(new Date(), 'No Check Schema For Cron Method ' + method);
630
+ return [4 /*yield*/, this.reportMethodError('SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], correlationId, { message: 'Missing check schema for cron method', method: method }, { context: 'callMethodCron-validation', method: method })];
631
+ case 5:
632
+ _d.sent();
633
+ throw new Error('No Check Schema For Cron Method ' + method);
634
+ case 6:
635
+ valObj = {};
636
+ valKeys = Object.keys(cronMethod.check._schema);
637
+ rootKeys = valKeys.filter(function (a) { return !a.includes('.'); });
638
+ for (i = 0; i < methodData.length; i++) {
639
+ valObj[rootKeys[i]] = methodData[i];
640
+ }
641
+ _d.label = 7;
642
+ case 7:
643
+ _d.trys.push([7, 8, , 10]);
644
+ cronMethod.check.validate(valObj);
645
+ return [3 /*break*/, 10];
646
+ case 8:
647
+ err_1 = _d.sent();
648
+ console.error(new Date(), 'Error in Cron Method Check (' + method + ')', err_1);
649
+ _a = (0, error_tracking_1.ensureErrorWithCorrelation)(err_1, correlationId), normalizedError = _a.error, resolvedCorrelationId = _a.correlationId;
650
+ return [4 /*yield*/, this.reportMethodError('SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], resolvedCorrelationId, {
651
+ message: 'Match error on cron method',
652
+ method: method,
653
+ data: valObj,
654
+ validationError: normalizedError
655
+ }, { context: 'callMethodCron-validation-error', method: method }, normalizedError.stack)];
656
+ case 9:
657
+ _d.sent();
658
+ normalizedError.message = "".concat(new Date().toISOString(), " - Error in Cron Method Check (").concat(method, "): ").concat(normalizedError.message);
659
+ throw normalizedError;
660
+ case 10:
661
+ monitor = this._monitorManagerFunction.startMonitorFunction('Cron Method', method, '', '', methodData);
662
+ _d.label = 11;
663
+ case 11:
664
+ _d.trys.push([11, 13, 15, 17]);
665
+ return [4 /*yield*/, (_c = cronMethod.function).call.apply(_c, __spreadArray([Object.assign({}, this, MethodManager.prototype, { id_user: '', user: '', id_ws: '' })], __read(methodData), false))];
666
+ case 12:
667
+ res = _d.sent();
668
+ return [2 /*return*/, res];
669
+ case 13:
670
+ err_2 = _d.sent();
671
+ _b = (0, error_tracking_1.ensureErrorWithCorrelation)(err_2, correlationId), normalizedError = _b.error, resolvedCorrelationId = _b.correlationId;
672
+ return [4 /*yield*/, this.reportMethodError('SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], resolvedCorrelationId, {
673
+ message: 'Error detected during cron method execution',
674
+ method: method,
675
+ data: methodData,
676
+ error: normalizedError
677
+ }, { context: 'callMethodCron-execution', method: method }, normalizedError.stack)];
678
+ case 14:
679
+ _d.sent();
680
+ normalizedError.message = "".concat(new Date().toISOString(), " - Error in Cron Method (").concat(method, "): ").concat(normalizedError.message);
681
+ throw normalizedError;
682
+ case 15: return [4 /*yield*/, this._monitorManagerFunction.finishMonitorFunction(monitor)];
683
+ case 16:
684
+ _d.sent();
685
+ return [7 /*endfinally*/];
686
+ case 17: return [2 /*return*/];
687
+ }
688
+ });
689
+ }); };
690
+ return [4 /*yield*/, (0, error_tracking_1.runWithCorrelationContext)(correlationId, execute)];
691
+ case 1: return [2 /*return*/, _a.sent()];
692
+ }
693
+ });
694
+ });
695
+ };
696
+ // Call/run method internal (No Emit on Socket)
697
+ MethodManager.prototype.callMethod = function (methodName) {
698
+ var methodData = [];
699
+ for (var _i = 1; _i < arguments.length; _i++) {
700
+ methodData[_i - 1] = arguments[_i];
701
+ }
702
+ return __awaiter(this, void 0, void 0, function () {
703
+ var existingCorrelationId, correlationId;
704
+ var _this = this;
705
+ return __generator(this, function (_a) {
706
+ switch (_a.label) {
707
+ case 0:
708
+ this._debugcallMethodHits += 1;
709
+ existingCorrelationId = (0, error_tracking_1.getCorrelationId)();
710
+ correlationId = existingCorrelationId || (0, common_1.objectIdHexString)();
711
+ return [4 /*yield*/, (0, error_tracking_1.runWithCorrelationContext)(correlationId, function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
712
+ switch (_a.label) {
713
+ case 0: return [4 /*yield*/, this.callMethodInternal(correlationId, methodName, methodData)];
714
+ case 1: return [2 /*return*/, _a.sent()];
715
+ }
716
+ }); }); })];
717
+ case 1: return [2 /*return*/, _a.sent()];
718
+ }
719
+ });
720
+ });
721
+ };
722
+ MethodManager.prototype.callMethodInternal = function (correlationId, methodName, methodData) {
723
+ return __awaiter(this, void 0, void 0, function () {
724
+ var method, shouldTrackTextMetric, textMetricProvider, releaseLocalConcurrency, methodCallback_1, functionMethodData_1, session, shouldStartTransaction, executeWithExistingSession_1, monitor_2;
725
+ var _this = this;
726
+ return __generator(this, function (_a) {
727
+ switch (_a.label) {
728
+ case 0:
729
+ method = this.getMethod(methodName);
730
+ if (!method) {
731
+ console.log('No Method: ' + methodName);
732
+ throw new Error("No Method: ".concat(methodName));
733
+ }
734
+ shouldTrackTextMetric = this.shouldTrackTextMessageMetric(methodName);
735
+ textMetricProvider = shouldTrackTextMetric ? this.getTextMessageProvider() : undefined;
736
+ return [4 /*yield*/, this.acquireLocalConcurrency(methodName, method.maxConcurrency)];
737
+ case 1:
738
+ releaseLocalConcurrency = _a.sent();
739
+ _a.label = 2;
740
+ case 2:
741
+ _a.trys.push([2, , 7, 8]);
742
+ if ((methodData.length > 1 || (methodData[0] && typeof methodData[0] !== 'function')) && !method.skipValidation) {
743
+ if (!method.check) {
744
+ console.error(new Date(), 'No Check Function For Method ' + methodName);
745
+ throw new Error("No Check Function For Method: ".concat(methodName));
746
+ }
747
+ else if (!method.check._schema) {
748
+ console.error(new Date(), 'No Check Schema For Method ' + methodName);
749
+ throw new Error("No Check Schema For Method: ".concat(methodName));
750
+ }
751
+ }
752
+ if (!(methodName !== 'insertSubscriptionLog' &&
753
+ methodName !== 'getDataURIfromURL' &&
754
+ methodName !== 'processAirdropDistribution' &&
755
+ methodName !== 'incCounter' &&
756
+ methodName !== 'supportCreateBillingUser' &&
757
+ methodName !== 'countCollectionWithQuery' &&
758
+ methodName !== 'countWithQuery' &&
759
+ methodName !== 'qbFetchRequests' &&
760
+ methodName !== 'qbHandleResponse')) return [3 /*break*/, 6];
761
+ if (!resolveio_server_app_1.ResolveIOServer.shouldWriteLogsOffline()) return [3 /*break*/, 3];
762
+ resolveio_server_app_1.ResolveIOServer.getLocalLogManager().writeLog({
763
+ type: 'log',
764
+ data: {
765
+ _id: (0, common_1.objectIdHexString)(),
766
+ createdAt: new Date(),
767
+ type: 'callMethod',
768
+ collection: '',
769
+ id_document: '',
770
+ payload: (0, common_1.getBinarySize)(JSON.stringify([methodData])) < 1000000 ? JSON.stringify([methodData], null, 2) : 'Too Big',
771
+ method: methodName,
772
+ id_user: this['id_user'] || '',
773
+ user: this['user'] || '',
774
+ messageId: 0,
775
+ route: '',
776
+ instance_index: process.env.NODE_APP_INSTANCE || '0',
777
+ correlationId: correlationId
778
+ }
779
+ });
780
+ return [3 /*break*/, 5];
781
+ case 3: return [4 /*yield*/, log_collection_1.Logs.insertOne({
782
+ _id: (0, common_1.objectIdHexString)(),
783
+ type: 'callMethod',
784
+ collection: '',
785
+ id_document: '',
786
+ payload: (0, common_1.getBinarySize)(JSON.stringify([methodData])) < 1000000 ? JSON.stringify([methodData], null, 2) : 'Too Big',
787
+ method: methodName,
788
+ id_user: this['id_user'] || '',
789
+ user: this['user'] || '',
790
+ messageId: 0,
791
+ route: '',
792
+ client: 'ResolveIO',
793
+ instance: resolveio_server_app_1.ResolveIOServer.getInstanceHost(),
794
+ instance_index: process.env.NODE_APP_INSTANCE || '0',
795
+ correlationId: correlationId
796
+ })];
797
+ case 4:
798
+ _a.sent();
799
+ _a.label = 5;
800
+ case 5:
801
+ ;
802
+ _a.label = 6;
803
+ case 6:
804
+ methodCallback_1 = typeof (methodData[methodData.length - 1]) === 'function' ? methodData[methodData.length - 1] : null;
805
+ functionMethodData_1 = methodCallback_1 ? methodData.slice(0, -1) : methodData;
806
+ session = resolveio_server_app_1.ResolveIOServer.getMongoManager().getSession();
807
+ shouldStartTransaction = !method.bypassSession &&
808
+ !session &&
809
+ ![
810
+ 'insertErrorLog', // CIRCULAR LOOP - DO NOT REMOVE
811
+ 'countWithQuery', // MONGO SESSIONS/TRANSACTIONS DONT WORK WITH COUNTS
812
+ 'sendEmail' // ALWAYS SEND SO ALWAYS HAVE RECORD - DONT ROLL BACK - BYPASS SESSION
813
+ ].includes(methodName) &&
814
+ !methodName.startsWith('monitor-') &&
815
+ !methodName.startsWith('log');
816
+ executeWithExistingSession_1 = function () { return __awaiter(_this, void 0, void 0, function () {
817
+ var monitor, res, error_3, err_3, _a, normalizedError, resolvedCorrelationId, error_4;
818
+ var _b;
819
+ return __generator(this, function (_c) {
820
+ switch (_c.label) {
821
+ case 0:
822
+ monitor = this._monitorManagerFunction.startMonitorFunction('Method', methodName, this['user'] || '', '', functionMethodData_1);
823
+ _c.label = 1;
824
+ case 1:
825
+ _c.trys.push([1, 7, 15, 17]);
826
+ return [4 /*yield*/, (_b = method.function).call.apply(_b, __spreadArray([Object.assign({}, this, MethodManager.prototype)], __read(functionMethodData_1), false))];
827
+ case 2:
828
+ res = _c.sent();
829
+ if (methodCallback_1) {
830
+ methodCallback_1(null, res);
831
+ }
832
+ if (!shouldTrackTextMetric) return [3 /*break*/, 6];
833
+ _c.label = 3;
834
+ case 3:
835
+ _c.trys.push([3, 5, , 6]);
836
+ return [4 /*yield*/, (0, communication_metric_manager_1.recordTextMessageMetric)({
837
+ status: 'sent',
838
+ provider: textMetricProvider,
839
+ metadata: {
840
+ method: methodName
841
+ }
842
+ })];
843
+ case 4:
844
+ _c.sent();
845
+ return [3 /*break*/, 6];
846
+ case 5:
847
+ error_3 = _c.sent();
848
+ console.error('Error recording text message metric:', error_3);
849
+ return [3 /*break*/, 6];
850
+ case 6: return [2 /*return*/, res];
851
+ case 7:
852
+ err_3 = _c.sent();
853
+ if (err_3.code === 112 || err_3.codeName === 'WriteConflict' || err_3.code === 251 || err_3.codeName === 'NoSuchTransaction') {
854
+ throw err_3; // Write error, retry
855
+ }
856
+ _a = (0, error_tracking_1.ensureErrorWithCorrelation)(err_3, correlationId), normalizedError = _a.error, resolvedCorrelationId = _a.correlationId;
857
+ console.log(JSON.stringify([new Date(), 'Error Method Manager - Run Method - Existing Session', methodName, {
858
+ code: normalizedError.code,
859
+ codeName: normalizedError.codeName,
860
+ message: normalizedError.message,
861
+ stack: normalizedError.stack,
862
+ correlationId: resolvedCorrelationId
863
+ }], null, 2));
864
+ return [4 /*yield*/, this.reportMethodError('SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], resolvedCorrelationId, {
865
+ message: 'Error detected during method execution (existing session)',
866
+ method: methodName,
867
+ data: methodData,
868
+ error: normalizedError
869
+ }, { context: 'callMethod-existing-session', methodName: methodName }, normalizedError.stack)];
870
+ case 8:
871
+ _c.sent();
872
+ normalizedError.message = "".concat(new Date().toISOString(), " - Error in Method (").concat(methodName, ") - Existing Session: ").concat(normalizedError.message);
873
+ if (methodCallback_1) {
874
+ methodCallback_1(normalizedError, null);
875
+ }
876
+ if (!shouldTrackTextMetric) return [3 /*break*/, 12];
877
+ _c.label = 9;
878
+ case 9:
879
+ _c.trys.push([9, 11, , 12]);
880
+ return [4 /*yield*/, (0, communication_metric_manager_1.recordTextMessageMetric)({
881
+ status: 'failed',
882
+ provider: textMetricProvider,
883
+ metadata: {
884
+ method: methodName
885
+ }
886
+ })];
887
+ case 10:
888
+ _c.sent();
889
+ return [3 /*break*/, 12];
890
+ case 11:
891
+ error_4 = _c.sent();
892
+ console.error('Error recording text message metric:', error_4);
893
+ return [3 /*break*/, 12];
894
+ case 12:
895
+ if (!!process.env.IS_WORKER_INSTANCE) return [3 /*break*/, 14];
896
+ return [4 /*yield*/, this.callMethod('insertErrorLog', "Error in Method: ".concat(methodName), {
897
+ method: methodName,
898
+ methodData: methodData,
899
+ error: {
900
+ message: normalizedError.message,
901
+ stack: normalizedError.stack,
902
+ code: normalizedError.code,
903
+ codeName: normalizedError.codeName
904
+ },
905
+ correlationId: resolvedCorrelationId
906
+ })];
907
+ case 13:
908
+ _c.sent();
909
+ _c.label = 14;
910
+ case 14: throw normalizedError;
911
+ case 15: return [4 /*yield*/, this._monitorManagerFunction.finishMonitorFunction(monitor)];
912
+ case 16:
913
+ _c.sent();
914
+ return [7 /*endfinally*/];
915
+ case 17: return [2 /*return*/];
916
+ }
917
+ });
918
+ }); };
919
+ if (shouldStartTransaction) {
920
+ monitor_2 = null;
921
+ return [2 /*return*/, resolveio_server_app_1.ResolveIOServer.getMongoManager().oneTimeTransaction(function () { return __awaiter(_this, void 0, void 0, function () {
922
+ var res, error_5, err_4, _a, normalizedError, resolvedCorrelationId, error_6;
923
+ var _b;
924
+ return __generator(this, function (_c) {
925
+ switch (_c.label) {
926
+ case 0:
927
+ // console.log(new Date(), 'Calling Method - New Session', methodName);
928
+ monitor_2 = this._monitorManagerFunction.startMonitorFunction('Method', methodName, this['user'] || '', '', functionMethodData_1);
929
+ _c.label = 1;
930
+ case 1:
931
+ _c.trys.push([1, 7, 15, 17]);
932
+ return [4 /*yield*/, (_b = method.function).call.apply(_b, __spreadArray([Object.assign({}, this, MethodManager.prototype)], __read(functionMethodData_1), false))];
933
+ case 2:
934
+ res = _c.sent();
935
+ if (methodCallback_1) {
936
+ methodCallback_1(null, res);
937
+ }
938
+ if (!shouldTrackTextMetric) return [3 /*break*/, 6];
939
+ _c.label = 3;
940
+ case 3:
941
+ _c.trys.push([3, 5, , 6]);
942
+ return [4 /*yield*/, (0, communication_metric_manager_1.recordTextMessageMetric)({
943
+ status: 'sent',
944
+ provider: textMetricProvider,
945
+ metadata: {
946
+ method: methodName
947
+ }
948
+ })];
949
+ case 4:
950
+ _c.sent();
951
+ return [3 /*break*/, 6];
952
+ case 5:
953
+ error_5 = _c.sent();
954
+ console.error('Error recording text message metric:', error_5);
955
+ return [3 /*break*/, 6];
956
+ case 6: return [2 /*return*/, res];
957
+ case 7:
958
+ err_4 = _c.sent();
959
+ if (err_4.code === 112 || err_4.codeName === 'WriteConflict' || err_4.code === 251 || err_4.codeName === 'NoSuchTransaction') {
960
+ throw err_4; // Write error, retry
961
+ }
962
+ _a = (0, error_tracking_1.ensureErrorWithCorrelation)(err_4, correlationId), normalizedError = _a.error, resolvedCorrelationId = _a.correlationId;
963
+ console.log(JSON.stringify([new Date(), 'Error Method Manager - Run Method - New Session', methodName, {
964
+ code: normalizedError.code,
965
+ codeName: normalizedError.codeName,
966
+ message: normalizedError.message,
967
+ stack: normalizedError.stack,
968
+ correlationId: resolvedCorrelationId
969
+ }], null, 2));
970
+ return [4 /*yield*/, this.reportMethodError('SERVER - Error Detected - ' + this.serverConfig['CLIENT_NAME'], resolvedCorrelationId, {
971
+ message: 'Error detected during method execution (new session)',
972
+ method: methodName,
973
+ data: methodData,
974
+ error: normalizedError
975
+ }, { context: 'callMethod-new-session', methodName: methodName }, normalizedError.stack)];
976
+ case 8:
977
+ _c.sent();
978
+ normalizedError.message = "".concat(new Date().toISOString(), " - Error in Method With Session (").concat(methodName, ") - New Session: ").concat(normalizedError.message);
979
+ if (methodCallback_1) {
980
+ methodCallback_1(normalizedError, null);
981
+ }
982
+ if (!shouldTrackTextMetric) return [3 /*break*/, 12];
983
+ _c.label = 9;
984
+ case 9:
985
+ _c.trys.push([9, 11, , 12]);
986
+ return [4 /*yield*/, (0, communication_metric_manager_1.recordTextMessageMetric)({
987
+ status: 'failed',
988
+ provider: textMetricProvider,
989
+ metadata: {
990
+ method: methodName
991
+ }
992
+ })];
993
+ case 10:
994
+ _c.sent();
995
+ return [3 /*break*/, 12];
996
+ case 11:
997
+ error_6 = _c.sent();
998
+ console.error('Error recording text message metric:', error_6);
999
+ return [3 /*break*/, 12];
1000
+ case 12:
1001
+ if (!!process.env.IS_WORKER_INSTANCE) return [3 /*break*/, 14];
1002
+ return [4 /*yield*/, this.callMethod('insertErrorLog', "Error in Method: ".concat(methodName), {
1003
+ method: methodName,
1004
+ methodData: methodData,
1005
+ error: {
1006
+ message: normalizedError.message,
1007
+ stack: normalizedError.stack,
1008
+ code: normalizedError.code,
1009
+ codeName: normalizedError.codeName
1010
+ },
1011
+ correlationId: resolvedCorrelationId
1012
+ })];
1013
+ case 13:
1014
+ _c.sent();
1015
+ _c.label = 14;
1016
+ case 14: throw normalizedError;
1017
+ case 15: return [4 /*yield*/, this._monitorManagerFunction.finishMonitorFunction(monitor_2)];
1018
+ case 16:
1019
+ _c.sent();
1020
+ return [7 /*endfinally*/];
1021
+ case 17: return [2 /*return*/];
1022
+ }
1023
+ });
1024
+ }); })];
1025
+ }
1026
+ else if (method.bypassSession && session) {
1027
+ return [2 /*return*/, resolveio_server_app_1.ResolveIOServer.getMongoManager().runWithoutSession(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
1028
+ switch (_a.label) {
1029
+ case 0: return [4 /*yield*/, executeWithExistingSession_1()];
1030
+ case 1: return [2 /*return*/, _a.sent()];
1031
+ }
1032
+ }); }); })];
1033
+ }
1034
+ else {
1035
+ return [2 /*return*/, executeWithExistingSession_1()];
1036
+ }
1037
+ return [3 /*break*/, 8];
1038
+ case 7:
1039
+ releaseLocalConcurrency();
1040
+ return [7 /*endfinally*/];
1041
+ case 8: return [2 /*return*/];
1042
+ }
1043
+ });
1044
+ });
1045
+ };
1046
+ MethodManager.prototype.acquireLocalConcurrency = function (methodName, maxConcurrency) {
1047
+ return __awaiter(this, void 0, void 0, function () {
1048
+ var current;
1049
+ var _this = this;
1050
+ return __generator(this, function (_a) {
1051
+ if (!maxConcurrency || maxConcurrency < 1) {
1052
+ return [2 /*return*/, function () { }];
1053
+ }
1054
+ current = this._localActiveCounts.get(methodName) || 0;
1055
+ if (current < maxConcurrency) {
1056
+ this._localActiveCounts.set(methodName, current + 1);
1057
+ return [2 /*return*/, this.createLocalRelease(methodName)];
1058
+ }
1059
+ // eslint-disable-next-line no-restricted-syntax
1060
+ return [2 /*return*/, new Promise(function (resolve) {
1061
+ var queue = _this._localWaitQueues.get(methodName);
1062
+ if (!queue) {
1063
+ queue = [];
1064
+ _this._localWaitQueues.set(methodName, queue);
1065
+ }
1066
+ queue.push(function () {
1067
+ var curr = _this._localActiveCounts.get(methodName) || 0;
1068
+ _this._localActiveCounts.set(methodName, curr + 1);
1069
+ resolve(_this.createLocalRelease(methodName));
1070
+ });
1071
+ })];
1072
+ });
1073
+ });
1074
+ };
1075
+ MethodManager.prototype.createLocalRelease = function (methodName) {
1076
+ var _this = this;
1077
+ var released = false;
1078
+ return function () {
1079
+ if (released) {
1080
+ return;
1081
+ }
1082
+ released = true;
1083
+ var current = _this._localActiveCounts.get(methodName) || 0;
1084
+ _this._localActiveCounts.set(methodName, current > 0 ? current - 1 : 0);
1085
+ var queue = _this._localWaitQueues.get(methodName);
1086
+ if (queue && queue.length) {
1087
+ var next = queue.shift();
1088
+ if (next) {
1089
+ next();
1090
+ }
1091
+ }
1092
+ };
1093
+ };
1094
+ MethodManager.prototype.setupEmailWatcher = function () {
1095
+ var _this = this;
1096
+ var changeStream = email_history_collection_1.EmailHistories.watchCollection([]);
1097
+ changeStream.on('change', function (change) { return __awaiter(_this, void 0, void 0, function () {
1098
+ var updatedEmail;
1099
+ return __generator(this, function (_a) {
1100
+ switch (_a.label) {
1101
+ case 0:
1102
+ if (!(change.operationType === 'insert' && change.fullDocument && change.fullDocument.status === 'pending')) return [3 /*break*/, 2];
1103
+ this.emailQueue.add(change.fullDocument._id.toString());
1104
+ return [4 /*yield*/, this.tryProcessEmail()];
1105
+ case 1:
1106
+ _a.sent();
1107
+ return [3 /*break*/, 3];
1108
+ case 2:
1109
+ if (change.operationType === 'update' || change.operationType === 'replace') {
1110
+ updatedEmail = change.fullDocument;
1111
+ if (updatedEmail && updatedEmail.status !== 'pending' && this.emailQueue.has(updatedEmail._id.toString())) {
1112
+ this.emailQueue.delete(updatedEmail._id.toString());
1113
+ }
1114
+ }
1115
+ _a.label = 3;
1116
+ case 3: return [2 /*return*/];
1117
+ }
1118
+ });
1119
+ }); })
1120
+ .on('error', function (err) { return __awaiter(_this, void 0, void 0, function () {
1121
+ return __generator(this, function (_a) {
1122
+ switch (_a.label) {
1123
+ case 0:
1124
+ console.error('Email history changestream error', err);
1125
+ return [4 /*yield*/, changeStream.close()];
1126
+ case 1:
1127
+ _a.sent();
1128
+ return [2 /*return*/];
1129
+ }
1130
+ });
1131
+ }); })
1132
+ .on('close', function () {
1133
+ _this.setupEmailWatcher();
1134
+ });
1135
+ };
1136
+ MethodManager.prototype.loadPendingEmails = function () {
1137
+ return __awaiter(this, void 0, void 0, function () {
1138
+ var pendingEmails, pendingEmails_1, pendingEmails_1_1, email;
1139
+ var e_1, _a;
1140
+ return __generator(this, function (_b) {
1141
+ switch (_b.label) {
1142
+ case 0: return [4 /*yield*/, email_history_collection_1.EmailHistories.find({ status: 'pending' }, { sort: { _id: 1 } })];
1143
+ case 1:
1144
+ pendingEmails = _b.sent();
1145
+ try {
1146
+ for (pendingEmails_1 = __values(pendingEmails), pendingEmails_1_1 = pendingEmails_1.next(); !pendingEmails_1_1.done; pendingEmails_1_1 = pendingEmails_1.next()) {
1147
+ email = pendingEmails_1_1.value;
1148
+ this.emailQueue.add(email._id.toString());
1149
+ }
1150
+ }
1151
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1152
+ finally {
1153
+ try {
1154
+ if (pendingEmails_1_1 && !pendingEmails_1_1.done && (_a = pendingEmails_1.return)) _a.call(pendingEmails_1);
1155
+ }
1156
+ finally { if (e_1) throw e_1.error; }
1157
+ }
1158
+ // Try to process emails
1159
+ return [4 /*yield*/, this.tryProcessEmail()];
1160
+ case 2:
1161
+ // Try to process emails
1162
+ _b.sent();
1163
+ return [2 /*return*/];
1164
+ }
1165
+ });
1166
+ });
1167
+ };
1168
+ MethodManager.prototype.tryProcessEmail = function () {
1169
+ return __awaiter(this, void 0, void 0, function () {
1170
+ var _loop_1, this_1, err_5;
1171
+ var _this = this;
1172
+ return __generator(this, function (_a) {
1173
+ switch (_a.label) {
1174
+ case 0:
1175
+ if (this.isEmailProcessing || this.emailQueue.size === 0) {
1176
+ return [2 /*return*/];
1177
+ }
1178
+ this.isEmailProcessing = true;
1179
+ _a.label = 1;
1180
+ case 1:
1181
+ _a.trys.push([1, 5, 6, 9]);
1182
+ _loop_1 = function () {
1183
+ var emailId, pendingEmail, queuedAt, timeSinceQueued, remainingDelay, emailHistory, validAttachments, attachmentError, _b, _c, att, response, arrayBuffer, buffer, maxSize, err_6, e_2_1, mailOptions, emailProvider;
1184
+ var e_2, _d;
1185
+ return __generator(this, function (_e) {
1186
+ switch (_e.label) {
1187
+ case 0:
1188
+ emailId = this_1.emailQueue.values().next().value;
1189
+ this_1.emailQueue.delete(emailId);
1190
+ return [4 /*yield*/, email_history_collection_1.EmailHistories.findOne({
1191
+ _id: emailId,
1192
+ status: 'pending',
1193
+ })];
1194
+ case 1:
1195
+ pendingEmail = _e.sent();
1196
+ if (!pendingEmail) {
1197
+ return [2 /*return*/, "continue"];
1198
+ }
1199
+ queuedAt = void 0;
1200
+ if (pendingEmail.date instanceof Date) {
1201
+ queuedAt = pendingEmail.date;
1202
+ }
1203
+ else if (pendingEmail.createdAt instanceof Date) {
1204
+ queuedAt = pendingEmail.createdAt;
1205
+ }
1206
+ else {
1207
+ queuedAt = new Date();
1208
+ }
1209
+ timeSinceQueued = Date.now() - queuedAt.getTime();
1210
+ remainingDelay = this_1._emailProcessingDelayMs - timeSinceQueued;
1211
+ if (!(remainingDelay > 0)) return [3 /*break*/, 3];
1212
+ // eslint-disable-next-line no-restricted-syntax
1213
+ return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, remainingDelay); })];
1214
+ case 2:
1215
+ // eslint-disable-next-line no-restricted-syntax
1216
+ _e.sent();
1217
+ _e.label = 3;
1218
+ case 3: return [4 /*yield*/, email_history_collection_1.EmailHistories.findOneAndUpdate({
1219
+ _id: emailId,
1220
+ status: 'pending',
1221
+ }, {
1222
+ $set: { status: 'processing', processingAt: new Date() },
1223
+ })];
1224
+ case 4:
1225
+ emailHistory = _e.sent();
1226
+ if (!emailHistory) {
1227
+ return [2 /*return*/, "continue"];
1228
+ }
1229
+ if (!(emailHistory.attachments && emailHistory.attachments.length > 0)) return [3 /*break*/, 18];
1230
+ validAttachments = [];
1231
+ attachmentError = false;
1232
+ _e.label = 5;
1233
+ case 5:
1234
+ _e.trys.push([5, 15, 16, 17]);
1235
+ _b = (e_2 = void 0, __values(emailHistory.attachments)), _c = _b.next();
1236
+ _e.label = 6;
1237
+ case 6:
1238
+ if (!!_c.done) return [3 /*break*/, 14];
1239
+ att = _c.value;
1240
+ if (!(att.path && att.path.startsWith('http'))) return [3 /*break*/, 12];
1241
+ _e.label = 7;
1242
+ case 7:
1243
+ _e.trys.push([7, 10, , 11]);
1244
+ return [4 /*yield*/, fetch(att.path)];
1245
+ case 8:
1246
+ response = _e.sent();
1247
+ if (!response.ok) {
1248
+ attachmentError = true;
1249
+ return [3 /*break*/, 13];
1250
+ }
1251
+ return [4 /*yield*/, response.arrayBuffer()];
1252
+ case 9:
1253
+ arrayBuffer = _e.sent();
1254
+ buffer = Buffer.from(arrayBuffer);
1255
+ maxSize = 20 * 1024 * 1024;
1256
+ if (buffer.length <= maxSize) {
1257
+ // Attachment is within size limits, include it
1258
+ att.content = buffer;
1259
+ delete att.path;
1260
+ validAttachments.push(att);
1261
+ }
1262
+ return [3 /*break*/, 11];
1263
+ case 10:
1264
+ err_6 = _e.sent();
1265
+ console.error('Failed to fetch attachment:', err_6);
1266
+ attachmentError = true;
1267
+ return [3 /*break*/, 11];
1268
+ case 11: return [3 /*break*/, 13];
1269
+ case 12:
1270
+ validAttachments.push(att);
1271
+ _e.label = 13;
1272
+ case 13:
1273
+ _c = _b.next();
1274
+ return [3 /*break*/, 6];
1275
+ case 14: return [3 /*break*/, 17];
1276
+ case 15:
1277
+ e_2_1 = _e.sent();
1278
+ e_2 = { error: e_2_1 };
1279
+ return [3 /*break*/, 17];
1280
+ case 16:
1281
+ try {
1282
+ if (_c && !_c.done && (_d = _b.return)) _d.call(_b);
1283
+ }
1284
+ finally { if (e_2) throw e_2.error; }
1285
+ return [7 /*endfinally*/];
1286
+ case 17:
1287
+ emailHistory.attachments = validAttachments;
1288
+ if (attachmentError) {
1289
+ emailHistory.text =
1290
+ (typeof emailHistory.text === 'string' ? emailHistory.text : '') +
1291
+ '\n\nCould not load attachments.';
1292
+ emailHistory.html =
1293
+ (typeof emailHistory.html === 'string' ? emailHistory.html : '') +
1294
+ '<p>Could not load attachments.</p>';
1295
+ }
1296
+ _e.label = 18;
1297
+ case 18:
1298
+ mailOptions = {
1299
+ replyTo: emailHistory.reply_to || (resolveio_server_app_1.ResolveIOServer.getServerConfig()['MAIL_REPLY_TO'] || undefined),
1300
+ from: emailHistory.send_from || resolveio_server_app_1.ResolveIOServer.getServerConfig().MAIL_FROM,
1301
+ to: emailHistory.email,
1302
+ subject: (resolveio_server_app_1.ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\/\/dev\./) ||
1303
+ resolveio_server_app_1.ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\/\/www\.dev\./)
1304
+ ? '(DEV SERVER) - '
1305
+ : '') + emailHistory.subject,
1306
+ text: typeof emailHistory.text === 'string' ? emailHistory.text : '',
1307
+ html: typeof emailHistory.html === 'string' ? emailHistory.html : '',
1308
+ attachments: emailHistory.attachments || [],
1309
+ force_ses: emailHistory.force_ses
1310
+ };
1311
+ // Process attachments before sending
1312
+ if (mailOptions.attachments && mailOptions.attachments.length > 0) {
1313
+ mailOptions.attachments = mailOptions.attachments.map(function (att) {
1314
+ var newAtt = __assign({}, att);
1315
+ // Handle attachments stored as BinData or Buffer
1316
+ if (newAtt.content && typeof newAtt.content === 'object' && !(newAtt.content instanceof Buffer)) {
1317
+ // Convert MongoDB's Binary data to Buffer
1318
+ if (newAtt.content._bsontype === 'Binary' && newAtt.content.sub_type === 0) {
1319
+ newAtt.content = Buffer.from(newAtt.content.buffer);
1320
+ }
1321
+ else {
1322
+ // Handle other types if necessary
1323
+ newAtt.content = Buffer.from(newAtt.content);
1324
+ }
1325
+ }
1326
+ // Handle attachments stored as Base64 strings
1327
+ else if (typeof newAtt.content === 'string' && newAtt.encoding === 'base64') {
1328
+ newAtt.content = Buffer.from(newAtt.content, 'base64');
1329
+ delete newAtt.encoding;
1330
+ }
1331
+ // Ensure the content is a Buffer
1332
+ else if (typeof newAtt.content === 'string') {
1333
+ newAtt.content = Buffer.from(newAtt.content);
1334
+ }
1335
+ return newAtt;
1336
+ });
1337
+ }
1338
+ emailProvider = (!mailOptions.force_ses && this_1._mailerCustom) ? 'custom' : 'ses';
1339
+ (!mailOptions.force_ses && this_1._mailerCustom ? this_1._mailerCustom : this_1._mailerSES).sendMail(mailOptions, function (err) { return __awaiter(_this, void 0, void 0, function () {
1340
+ var metricStatus, error_7, error_8;
1341
+ return __generator(this, function (_a) {
1342
+ switch (_a.label) {
1343
+ case 0:
1344
+ metricStatus = err ? 'failed' : 'sent';
1345
+ _a.label = 1;
1346
+ case 1:
1347
+ _a.trys.push([1, 8, 10, 14]);
1348
+ if (!err) return [3 /*break*/, 3];
1349
+ console.error('Failed to send email:', err);
1350
+ return [4 /*yield*/, email_history_collection_1.EmailHistories.updateOne({ _id: emailHistory._id }, {
1351
+ $set: {
1352
+ status: 'failed',
1353
+ error: typeof err === 'string' ? err : this.safeStringify(err),
1354
+ completedAt: new Date(),
1355
+ },
1356
+ })];
1357
+ case 2:
1358
+ _a.sent();
1359
+ return [3 /*break*/, 7];
1360
+ case 3:
1361
+ if (!(emailHistory.email === 'dev@resolveio.com')) return [3 /*break*/, 5];
1362
+ return [4 /*yield*/, email_history_collection_1.EmailHistories.deleteOne({ _id: emailHistory._id })];
1363
+ case 4:
1364
+ _a.sent();
1365
+ return [3 /*break*/, 7];
1366
+ case 5: return [4 /*yield*/, email_history_collection_1.EmailHistories.updateOne({ _id: emailHistory._id }, {
1367
+ $set: {
1368
+ status: 'completed',
1369
+ completedAt: new Date(),
1370
+ },
1371
+ })];
1372
+ case 6:
1373
+ _a.sent();
1374
+ _a.label = 7;
1375
+ case 7: return [3 /*break*/, 14];
1376
+ case 8:
1377
+ error_7 = _a.sent();
1378
+ console.error('Error in sendMail callback:', error_7);
1379
+ return [4 /*yield*/, email_history_collection_1.EmailHistories.updateOne({ _id: emailHistory._id }, {
1380
+ $set: {
1381
+ status: 'failed',
1382
+ error: typeof error_7 === 'string' ? error_7 : this.safeStringify(error_7),
1383
+ completedAt: new Date(),
1384
+ },
1385
+ })];
1386
+ case 9:
1387
+ _a.sent();
1388
+ return [3 /*break*/, 14];
1389
+ case 10:
1390
+ _a.trys.push([10, 12, , 13]);
1391
+ return [4 /*yield*/, (0, communication_metric_manager_1.recordEmailMetric)({
1392
+ status: metricStatus,
1393
+ provider: emailProvider,
1394
+ metadata: {
1395
+ method: 'sendEmail'
1396
+ }
1397
+ })];
1398
+ case 11:
1399
+ _a.sent();
1400
+ return [3 /*break*/, 13];
1401
+ case 12:
1402
+ error_8 = _a.sent();
1403
+ console.error('Error recording email metric:', error_8);
1404
+ return [3 /*break*/, 13];
1405
+ case 13: return [7 /*endfinally*/];
1406
+ case 14: return [2 /*return*/];
1407
+ }
1408
+ });
1409
+ }); });
1410
+ // Wait for at least one second before sending the next email
1411
+ // eslint-disable-next-line no-restricted-syntax
1412
+ return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 1000); })];
1413
+ case 19:
1414
+ // Wait for at least one second before sending the next email
1415
+ // eslint-disable-next-line no-restricted-syntax
1416
+ _e.sent();
1417
+ return [2 /*return*/];
1418
+ }
1419
+ });
1420
+ };
1421
+ this_1 = this;
1422
+ _a.label = 2;
1423
+ case 2:
1424
+ if (!(this.emailQueue.size > 0)) return [3 /*break*/, 4];
1425
+ return [5 /*yield**/, _loop_1()];
1426
+ case 3:
1427
+ _a.sent();
1428
+ return [3 /*break*/, 2];
1429
+ case 4: return [3 /*break*/, 9];
1430
+ case 5:
1431
+ err_5 = _a.sent();
1432
+ console.error('Error processing email queue:', err_5);
1433
+ return [3 /*break*/, 9];
1434
+ case 6:
1435
+ this.isEmailProcessing = false;
1436
+ if (!(this.emailQueue.size > 0)) return [3 /*break*/, 8];
1437
+ return [4 /*yield*/, this.tryProcessEmail()];
1438
+ case 7:
1439
+ _a.sent();
1440
+ _a.label = 8;
1441
+ case 8: return [7 /*endfinally*/];
1442
+ case 9: return [2 /*return*/];
1443
+ }
1444
+ });
1445
+ });
1446
+ };
1447
+ MethodManager.prototype.shouldTrackTextMessageMetric = function (methodName) {
1448
+ var normalized = String(methodName || '').trim().toLowerCase();
1449
+ if (!normalized) {
1450
+ return false;
1451
+ }
1452
+ return normalized.startsWith('sendsms') || normalized.startsWith('sendtext');
1453
+ };
1454
+ MethodManager.prototype.getTextMessageProvider = function () {
1455
+ var _a, _b, _c;
1456
+ var provider = ((_a = this.serverConfig) === null || _a === void 0 ? void 0 : _a['SMS_PROVIDER']) || '';
1457
+ if (typeof provider === 'string' && provider.trim().length) {
1458
+ return provider.trim().toLowerCase();
1459
+ }
1460
+ if (((_b = this.serverConfig) === null || _b === void 0 ? void 0 : _b['TWILIO_SID']) || ((_c = this.serverConfig) === null || _c === void 0 ? void 0 : _c['TWILIO_AUTH_TOKEN'])) {
1461
+ return 'twilio';
1462
+ }
1463
+ return undefined;
1464
+ };
1465
+ MethodManager.prototype.safeStringify = function (obj) {
1466
+ try {
1467
+ return JSON.stringify(obj, this.getCircularReplacer());
1468
+ }
1469
+ catch (e) {
1470
+ return "Error in JSON stringifying: ".concat(e.message);
1471
+ }
1472
+ };
1473
+ MethodManager.prototype.getCircularReplacer = function () {
1474
+ var seen = new WeakSet();
1475
+ return function (key, value) {
1476
+ if (typeof value === "object" && value !== null) {
1477
+ if (seen.has(value)) {
1478
+ return "[Circular]";
1479
+ }
1480
+ seen.add(value);
1481
+ }
1482
+ return value;
1483
+ };
1484
+ };
1485
+ MethodManager.prototype.tryMergeEmailOccurrence = function (email, subject, correlationId, occurrence, meta) {
1486
+ return __awaiter(this, void 0, void 0, function () {
1487
+ var existing, normalizedOccurrences, _a, aggregatedText, aggregatedHtml, updated;
1488
+ return __generator(this, function (_b) {
1489
+ switch (_b.label) {
1490
+ case 0: return [4 /*yield*/, email_history_collection_1.EmailHistories.findOne({
1491
+ email: email,
1492
+ correlationId: correlationId,
1493
+ status: 'pending'
1494
+ }, { sort: { date: 1 } })];
1495
+ case 1:
1496
+ existing = _b.sent();
1497
+ if (!existing) {
1498
+ return [2 /*return*/, null];
1499
+ }
1500
+ normalizedOccurrences = Array.isArray(existing.occurrences) && existing.occurrences.length
1501
+ ? existing.occurrences.map(function (item) { return ({
1502
+ _id: item._id || (0, common_1.objectIdHexString)(),
1503
+ createdAt: item.createdAt instanceof Date ? item.createdAt : new Date(item.createdAt),
1504
+ subject: item.subject || existing.subject || '',
1505
+ text: item.text,
1506
+ html: item.html,
1507
+ meta: item.meta
1508
+ }); })
1509
+ : [createEmailOccurrence(existing.subject || '', typeof existing.text === 'string' ? existing.text : undefined, typeof existing.html === 'string' ? existing.html : undefined, existing.meta)];
1510
+ normalizedOccurrences.push(occurrence);
1511
+ _a = formatGroupedEmailContent(correlationId, normalizedOccurrences), aggregatedText = _a.text, aggregatedHtml = _a.html;
1512
+ return [4 /*yield*/, email_history_collection_1.EmailHistories.findOneAndUpdate({
1513
+ _id: existing._id,
1514
+ status: 'pending'
1515
+ }, {
1516
+ $set: {
1517
+ subject: subject,
1518
+ text: aggregatedText,
1519
+ html: aggregatedHtml,
1520
+ occurrences: normalizedOccurrences,
1521
+ meta: meta || existing.meta,
1522
+ updatedAt: new Date()
1523
+ }
1524
+ }, { returnDocument: 'after' })];
1525
+ case 2:
1526
+ updated = _b.sent();
1527
+ return [2 /*return*/, updated || null];
1528
+ }
1529
+ });
1530
+ });
1531
+ };
1532
+ MethodManager.prototype.sendEmail = function (sendTo_1, subject_1, text_1, html_1, attachments_1, send_from_1, reply_to_1) {
1533
+ return __awaiter(this, arguments, void 0, function (sendTo, subject, text, html, attachments, send_from, reply_to, force_ses, local_override, options) {
1534
+ var normalizedSubject, correlationId, finalSubject, groupByCorrelationId, normalizedText, normalizedHtml, occurrence, allowGrouping, normalizedAttachments, merged, emailHistory, _a, aggregatedText, aggregatedHtml, history_1, err_7;
1535
+ if (force_ses === void 0) { force_ses = false; }
1536
+ if (local_override === void 0) { local_override = false; }
1537
+ return __generator(this, function (_b) {
1538
+ switch (_b.label) {
1539
+ case 0:
1540
+ // Modify sendTo in development environments
1541
+ if ((resolveio_server_app_1.ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\/\/dev\./) ||
1542
+ resolveio_server_app_1.ResolveIOServer.getServerConfig()['ROOT_URL'].match(/https:\/\/www\.dev\./) ||
1543
+ resolveio_server_app_1.ResolveIOServer.getServerConfig()['ROOT_URL'] === 'http://localhost:4200') &&
1544
+ !sendTo.match(/\@resolveio\.com/)) {
1545
+ sendTo = 'dev@resolveio.com';
1546
+ }
1547
+ normalizedSubject = subject || '';
1548
+ correlationId = options === null || options === void 0 ? void 0 : options.correlationId;
1549
+ finalSubject = appendCorrelationIdToSubject(normalizedSubject, correlationId);
1550
+ groupByCorrelationId = !!correlationId;
1551
+ normalizedText = typeof text === 'string' ? text : '';
1552
+ normalizedHtml = typeof html === 'string' ? html : '';
1553
+ occurrence = groupByCorrelationId
1554
+ ? createEmailOccurrence(normalizedSubject, normalizedText, normalizedHtml, options === null || options === void 0 ? void 0 : options.meta)
1555
+ : null;
1556
+ allowGrouping = groupByCorrelationId;
1557
+ if (!sendTo) return [3 /*break*/, 9];
1558
+ if (!(resolveio_server_app_1.ResolveIOServer.getServerConfig()['ROOT_URL'] !== 'http://localhost:4200' ||
1559
+ local_override)) return [3 /*break*/, 7];
1560
+ normalizedAttachments = [];
1561
+ if (Array.isArray(attachments)) {
1562
+ normalizedAttachments = attachments.slice();
1563
+ }
1564
+ else if (attachments) {
1565
+ normalizedAttachments = [attachments];
1566
+ }
1567
+ normalizedAttachments = normalizedAttachments.map(function (att) {
1568
+ var newAtt = __assign({}, att);
1569
+ if (Buffer.isBuffer(newAtt.content)) {
1570
+ newAtt.content = newAtt.content.toString('base64');
1571
+ newAtt.encoding = 'base64';
1572
+ }
1573
+ return newAtt;
1574
+ });
1575
+ if (normalizedAttachments.length > 0) {
1576
+ allowGrouping = false;
1577
+ }
1578
+ if (!(allowGrouping && occurrence && correlationId)) return [3 /*break*/, 2];
1579
+ return [4 /*yield*/, this.tryMergeEmailOccurrence(sendTo, finalSubject, correlationId, occurrence, options === null || options === void 0 ? void 0 : options.meta)];
1580
+ case 1:
1581
+ merged = _b.sent();
1582
+ if (merged) {
1583
+ return [2 /*return*/, merged];
1584
+ }
1585
+ _b.label = 2;
1586
+ case 2:
1587
+ emailHistory = {
1588
+ _id: (0, common_1.objectIdHexString)(),
1589
+ __v: 0,
1590
+ date: new Date(),
1591
+ id_user: this['id_user'] || '',
1592
+ user: this['user'] || '',
1593
+ email: sendTo,
1594
+ subject: finalSubject,
1595
+ text: normalizedText,
1596
+ html: normalizedHtml,
1597
+ attachments: normalizedAttachments,
1598
+ send_from: send_from || '',
1599
+ reply_to: reply_to || '',
1600
+ status: 'pending',
1601
+ error: '',
1602
+ force_ses: force_ses
1603
+ };
1604
+ if (allowGrouping && occurrence && correlationId) {
1605
+ _a = formatGroupedEmailContent(correlationId, [occurrence]), aggregatedText = _a.text, aggregatedHtml = _a.html;
1606
+ emailHistory.text = aggregatedText;
1607
+ emailHistory.html = aggregatedHtml;
1608
+ emailHistory.occurrences = [occurrence];
1609
+ emailHistory.correlationId = correlationId;
1610
+ if (options === null || options === void 0 ? void 0 : options.meta) {
1611
+ emailHistory.meta = options.meta;
1612
+ }
1613
+ }
1614
+ else {
1615
+ if (correlationId) {
1616
+ emailHistory.correlationId = correlationId;
1617
+ }
1618
+ if (options === null || options === void 0 ? void 0 : options.meta) {
1619
+ emailHistory.meta = options.meta;
1620
+ }
1621
+ }
1622
+ _b.label = 3;
1623
+ case 3:
1624
+ _b.trys.push([3, 5, , 6]);
1625
+ return [4 /*yield*/, email_history_collection_1.EmailHistories.insertOne(emailHistory)];
1626
+ case 4:
1627
+ history_1 = _b.sent();
1628
+ return [2 /*return*/, history_1];
1629
+ case 5:
1630
+ err_7 = _b.sent();
1631
+ console.error('Failed to queue email:', err_7);
1632
+ err_7.message = "Failed to queue email: ".concat(err_7.message);
1633
+ throw err_7;
1634
+ case 6: return [3 /*break*/, 8];
1635
+ case 7:
1636
+ console.log('Send email', sendTo, finalSubject, normalizedText, normalizedHtml, attachments, send_from, force_ses, correlationId);
1637
+ return [2 /*return*/, true];
1638
+ case 8: return [3 /*break*/, 10];
1639
+ case 9: return [2 /*return*/, true];
1640
+ case 10: return [2 /*return*/];
1641
+ }
1642
+ });
1643
+ });
1644
+ };
1645
+ MethodManager.prototype.getAWS = function () {
1646
+ return this._aws;
1647
+ };
1648
+ MethodManager.prototype.readFile = function (fileName) {
1649
+ if (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {
1650
+ try {
1651
+ return fs.readFileSync(path.join(__dirname, ('../private/' + fileName)), 'utf-8');
1652
+ }
1653
+ catch (err) {
1654
+ err.message = "Error in readFile: ".concat(err.message);
1655
+ throw err;
1656
+ }
1657
+ }
1658
+ else {
1659
+ if (fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {
1660
+ try {
1661
+ return fs.readFileSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'utf-8');
1662
+ }
1663
+ catch (err) {
1664
+ err.message = "Error in readFile: ".concat(err.message);
1665
+ throw err;
1666
+ }
1667
+ }
1668
+ }
1669
+ throw new Error('Error in readFile: File Not Found');
1670
+ };
1671
+ MethodManager.prototype.readImage = function (fileName) {
1672
+ if (fs.existsSync(path.join(__dirname, ('../private/' + fileName)))) {
1673
+ try {
1674
+ return fs.readFileSync(path.join(__dirname, ('../private/' + fileName)), 'base64');
1675
+ }
1676
+ catch (err) {
1677
+ err.message = "Error in readImage: ".concat(err.message);
1678
+ throw err;
1679
+ }
1680
+ }
1681
+ else {
1682
+ if (fs.existsSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(), ('./private/' + fileName)))) {
1683
+ try {
1684
+ return fs.readFileSync(path.join(resolveio_server_app_1.ResolveIOServer.getClientDir(), ('./private/' + fileName)), 'base64');
1685
+ }
1686
+ catch (err) {
1687
+ err.message = "Error in readImage: ".concat(err.message);
1688
+ throw err;
1689
+ }
1690
+ }
1691
+ }
1692
+ throw new Error('Error in readImage: File Not Found');
1693
+ };
1694
+ MethodManager.prototype.getEnableDebug = function () {
1695
+ return this._enableDebug;
1696
+ };
1697
+ return MethodManager;
1698
+ }());
1699
+ exports.MethodManager = MethodManager;
1700
+
1701
+ //# sourceMappingURL=method.manager.js.map