@resolveio/server-lib 22.3.3 → 22.3.5

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