@resolveio/server-lib 22.3.221 → 22.3.222

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