@resolveio/server-lib 22.2.34 → 22.2.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (649) hide show
  1. package/ai/assistant-core-heuristics.d.ts +11 -0
  2. package/ai/assistant-core-heuristics.js +531 -0
  3. package/ai/assistant-core-heuristics.js.map +1 -0
  4. package/client-server-app.d.ts +1 -0
  5. package/client-server-app.js +68 -0
  6. package/client-server-app.js.map +1 -0
  7. package/collections/ai-terminal-conversation.collection.d.ts +2 -0
  8. package/collections/ai-terminal-conversation.collection.js +140 -0
  9. package/collections/ai-terminal-conversation.collection.js.map +1 -0
  10. package/collections/ai-terminal-issue-report.collection.d.ts +2 -0
  11. package/collections/ai-terminal-issue-report.collection.js +148 -0
  12. package/collections/ai-terminal-issue-report.collection.js.map +1 -0
  13. package/collections/ai-terminal-message.collection.d.ts +2 -0
  14. package/collections/ai-terminal-message.collection.js +121 -0
  15. package/collections/ai-terminal-message.collection.js.map +1 -0
  16. package/collections/app-setting.collection.d.ts +3 -0
  17. package/collections/app-setting.collection.js +103 -0
  18. package/collections/app-setting.collection.js.map +1 -0
  19. package/collections/app-status.collection.d.ts +3 -0
  20. package/collections/app-status.collection.js +57 -0
  21. package/collections/app-status.collection.js.map +1 -0
  22. package/collections/communication-metric.collection.d.ts +2 -0
  23. package/collections/communication-metric.collection.js +133 -0
  24. package/collections/communication-metric.collection.js.map +1 -0
  25. package/collections/counter.collection.d.ts +3 -0
  26. package/collections/counter.collection.js +56 -0
  27. package/collections/counter.collection.js.map +1 -0
  28. package/collections/cron-job-history.collection.d.ts +3 -0
  29. package/collections/cron-job-history.collection.js +137 -0
  30. package/collections/cron-job-history.collection.js.map +1 -0
  31. package/collections/cron-job.collection.d.ts +3 -0
  32. package/collections/cron-job.collection.js +92 -0
  33. package/collections/cron-job.collection.js.map +1 -0
  34. package/collections/customer-notification.collection.d.ts +3 -0
  35. package/collections/customer-notification.collection.js +130 -0
  36. package/collections/customer-notification.collection.js.map +1 -0
  37. package/collections/customer-portal-password.collection.d.ts +3 -0
  38. package/collections/customer-portal-password.collection.js +75 -0
  39. package/collections/customer-portal-password.collection.js.map +1 -0
  40. package/collections/email-history.collection.d.ts +3 -0
  41. package/collections/email-history.collection.js +121 -0
  42. package/collections/email-history.collection.js.map +1 -0
  43. package/collections/email-verified.collection.d.ts +3 -0
  44. package/collections/email-verified.collection.js +61 -0
  45. package/collections/email-verified.collection.js.map +1 -0
  46. package/collections/file.collection.d.ts +3 -0
  47. package/collections/file.collection.js +74 -0
  48. package/collections/file.collection.js.map +1 -0
  49. package/collections/flag-update.collection.d.ts +3 -0
  50. package/collections/flag-update.collection.js +57 -0
  51. package/collections/flag-update.collection.js.map +1 -0
  52. package/collections/flag.collection.d.ts +3 -0
  53. package/collections/flag.collection.js +57 -0
  54. package/collections/flag.collection.js.map +1 -0
  55. package/collections/log-method-latency.collection.d.ts +3 -0
  56. package/collections/log-method-latency.collection.js +77 -0
  57. package/collections/log-method-latency.collection.js.map +1 -0
  58. package/collections/log-subscription.collection.d.ts +3 -0
  59. package/collections/log-subscription.collection.js +80 -0
  60. package/collections/log-subscription.collection.js.map +1 -0
  61. package/collections/log.collection.d.ts +3 -0
  62. package/collections/log.collection.js +93 -0
  63. package/collections/log.collection.js.map +1 -0
  64. package/collections/logged-in-users.collection.d.ts +3 -0
  65. package/collections/logged-in-users.collection.js +67 -0
  66. package/collections/logged-in-users.collection.js.map +1 -0
  67. package/collections/monitor-cpu.collection.d.ts +3 -0
  68. package/collections/monitor-cpu.collection.js +65 -0
  69. package/collections/monitor-cpu.collection.js.map +1 -0
  70. package/collections/monitor-function.collection.d.ts +3 -0
  71. package/collections/monitor-function.collection.js +74 -0
  72. package/collections/monitor-function.collection.js.map +1 -0
  73. package/collections/monitor-memory.collection.d.ts +3 -0
  74. package/collections/monitor-memory.collection.js +77 -0
  75. package/collections/monitor-memory.collection.js.map +1 -0
  76. package/collections/monitor-mongo.collection.d.ts +3 -0
  77. package/collections/monitor-mongo.collection.js +71 -0
  78. package/collections/monitor-mongo.collection.js.map +1 -0
  79. package/collections/notification.collection.d.ts +3 -0
  80. package/collections/notification.collection.js +57 -0
  81. package/collections/notification.collection.js.map +1 -0
  82. package/collections/openai-usage-ledger.collection.d.ts +2 -0
  83. package/collections/openai-usage-ledger.collection.js +124 -0
  84. package/collections/openai-usage-ledger.collection.js.map +1 -0
  85. package/collections/report-builder-dashboard-builder.collection.d.ts +3 -0
  86. package/collections/report-builder-dashboard-builder.collection.js +109 -0
  87. package/collections/report-builder-dashboard-builder.collection.js.map +1 -0
  88. package/collections/report-builder-library.collection.d.ts +3 -0
  89. package/collections/report-builder-library.collection.js +87 -0
  90. package/collections/report-builder-library.collection.js.map +1 -0
  91. package/collections/report-builder-report.collection.d.ts +4 -0
  92. package/collections/report-builder-report.collection.js +180 -0
  93. package/collections/report-builder-report.collection.js.map +1 -0
  94. package/collections/user-group.collection.d.ts +4 -0
  95. package/collections/user-group.collection.js +89 -0
  96. package/collections/user-group.collection.js.map +1 -0
  97. package/collections/user-guide.collection.d.ts +3 -0
  98. package/collections/user-guide.collection.js +57 -0
  99. package/collections/user-guide.collection.js.map +1 -0
  100. package/collections/user.collection.d.ts +4 -0
  101. package/collections/user.collection.js +180 -0
  102. package/collections/user.collection.js.map +1 -0
  103. package/cron/cron.d.ts +14 -0
  104. package/cron/cron.js +216 -0
  105. package/cron/cron.js.map +1 -0
  106. package/fixtures/cron-jobs.d.ts +1 -0
  107. package/fixtures/cron-jobs.js +150 -0
  108. package/fixtures/cron-jobs.js.map +1 -0
  109. package/fixtures/init.d.ts +1 -0
  110. package/fixtures/init.js +91 -0
  111. package/fixtures/init.js.map +1 -0
  112. package/http/auth.d.ts +2 -0
  113. package/http/auth.js +903 -0
  114. package/http/auth.js.map +1 -0
  115. package/http/health.d.ts +1 -0
  116. package/http/health.js +11 -0
  117. package/http/health.js.map +1 -0
  118. package/http/home.d.ts +1 -0
  119. package/http/home.js +134 -0
  120. package/http/home.js.map +1 -0
  121. package/http/slow-query-publication.d.ts +2 -0
  122. package/http/slow-query-publication.js +99 -0
  123. package/http/slow-query-publication.js.map +1 -0
  124. package/index.d.ts +1 -0
  125. package/index.js +19 -0
  126. package/index.js.map +1 -0
  127. package/managers/communication-metric.manager.d.ts +16 -0
  128. package/managers/communication-metric.manager.js +134 -0
  129. package/managers/communication-metric.manager.js.map +1 -0
  130. package/managers/cron.manager.d.ts +20 -0
  131. package/managers/cron.manager.js +534 -0
  132. package/managers/cron.manager.js.map +1 -0
  133. package/managers/customer-notification-content.manager.d.ts +55 -0
  134. package/managers/customer-notification-content.manager.js +158 -0
  135. package/managers/customer-notification-content.manager.js.map +1 -0
  136. package/managers/diagnostic-manager-bootstrap.d.ts +9 -0
  137. package/managers/diagnostic-manager-bootstrap.js +260 -0
  138. package/managers/diagnostic-manager-bootstrap.js.map +1 -0
  139. package/managers/error-auto-fix.manager.d.ts +149 -0
  140. package/managers/error-auto-fix.manager.js +3064 -0
  141. package/managers/error-auto-fix.manager.js.map +1 -0
  142. package/managers/local-log.manager.d.ts +18 -0
  143. package/managers/local-log.manager.js +88 -0
  144. package/managers/local-log.manager.js.map +1 -0
  145. package/managers/method.manager.d.ts +77 -0
  146. package/managers/method.manager.js +1701 -0
  147. package/managers/method.manager.js.map +1 -0
  148. package/managers/mongo.manager.d.ts +222 -0
  149. package/managers/mongo.manager.js +4984 -0
  150. package/managers/mongo.manager.js.map +1 -0
  151. package/managers/monitor.manager.d.ts +69 -0
  152. package/managers/monitor.manager.js +534 -0
  153. package/managers/monitor.manager.js.map +1 -0
  154. package/managers/openai-usage-ledger.manager.d.ts +15 -0
  155. package/managers/openai-usage-ledger.manager.js +144 -0
  156. package/managers/openai-usage-ledger.manager.js.map +1 -0
  157. package/managers/slow-query-verifier.manager.d.ts +144 -0
  158. package/managers/slow-query-verifier.manager.js +3857 -0
  159. package/managers/slow-query-verifier.manager.js.map +1 -0
  160. package/managers/slow-query.manager.d.ts +28 -0
  161. package/managers/slow-query.manager.js +468 -0
  162. package/managers/slow-query.manager.js.map +1 -0
  163. package/managers/subscription.manager.d.ts +169 -0
  164. package/managers/subscription.manager.js +3422 -0
  165. package/managers/subscription.manager.js.map +1 -0
  166. package/managers/websocket.manager.d.ts +73 -0
  167. package/managers/websocket.manager.js +673 -0
  168. package/managers/websocket.manager.js.map +1 -0
  169. package/managers/worker-dispatcher.manager.d.ts +117 -0
  170. package/managers/worker-dispatcher.manager.js +1210 -0
  171. package/managers/worker-dispatcher.manager.js.map +1 -0
  172. package/managers/worker-server.manager.d.ts +16 -0
  173. package/managers/worker-server.manager.js +530 -0
  174. package/managers/worker-server.manager.js.map +1 -0
  175. package/methods/accounts.d.ts +2 -0
  176. package/methods/accounts.js +624 -0
  177. package/methods/accounts.js.map +1 -0
  178. package/methods/ai-terminal.d.ts +304 -0
  179. package/methods/ai-terminal.js +25096 -0
  180. package/methods/ai-terminal.js.map +1 -0
  181. package/methods/app-settings.d.ts +2 -0
  182. package/methods/app-settings.js +169 -0
  183. package/methods/app-settings.js.map +1 -0
  184. package/methods/aws.d.ts +2 -0
  185. package/methods/aws.js +874 -0
  186. package/methods/aws.js.map +1 -0
  187. package/methods/collections.d.ts +2 -0
  188. package/methods/collections.js +626 -0
  189. package/methods/collections.js.map +1 -0
  190. package/methods/counters.d.ts +2 -0
  191. package/methods/counters.js +111 -0
  192. package/methods/counters.js.map +1 -0
  193. package/methods/cron-jobs.d.ts +2 -0
  194. package/methods/cron-jobs.js +2471 -0
  195. package/methods/cron-jobs.js.map +1 -0
  196. package/methods/customer-notifications.d.ts +2 -0
  197. package/methods/customer-notifications.js +528 -0
  198. package/methods/customer-notifications.js.map +1 -0
  199. package/methods/diagnostics.d.ts +2 -0
  200. package/methods/diagnostics.js +514 -0
  201. package/methods/diagnostics.js.map +1 -0
  202. package/methods/flag-updates.d.ts +2 -0
  203. package/methods/flag-updates.js +8 -0
  204. package/methods/flag-updates.js.map +1 -0
  205. package/methods/flags.d.ts +2 -0
  206. package/methods/flags.js +8 -0
  207. package/methods/flags.js.map +1 -0
  208. package/methods/logs.d.ts +2 -0
  209. package/methods/logs.js +750 -0
  210. package/methods/logs.js.map +1 -0
  211. package/methods/mongo-explorer.d.ts +2 -0
  212. package/methods/mongo-explorer.js +1811 -0
  213. package/methods/mongo-explorer.js.map +1 -0
  214. package/methods/monitor.d.ts +2 -0
  215. package/methods/monitor.js +543 -0
  216. package/methods/monitor.js.map +1 -0
  217. package/methods/pdf.d.ts +2 -0
  218. package/methods/pdf.js +1195 -0
  219. package/methods/pdf.js.map +1 -0
  220. package/methods/publications.d.ts +1 -0
  221. package/methods/publications.js +183 -0
  222. package/methods/publications.js.map +1 -0
  223. package/methods/report-builder.d.ts +2 -0
  224. package/methods/report-builder.js +3099 -0
  225. package/methods/report-builder.js.map +1 -0
  226. package/methods/support.d.ts +2 -0
  227. package/methods/support.js +313 -0
  228. package/methods/support.js.map +1 -0
  229. package/models/ai-terminal-conversation.model.d.ts +17 -0
  230. package/models/ai-terminal-conversation.model.js +4 -0
  231. package/models/ai-terminal-conversation.model.js.map +1 -0
  232. package/models/ai-terminal-issue-report.model.d.ts +19 -0
  233. package/models/ai-terminal-issue-report.model.js +4 -0
  234. package/models/ai-terminal-issue-report.model.js.map +1 -0
  235. package/models/ai-terminal-message.model.d.ts +22 -0
  236. package/models/ai-terminal-message.model.js +4 -0
  237. package/models/ai-terminal-message.model.js.map +1 -0
  238. package/models/app-setting.model.d.ts +16 -0
  239. package/models/app-setting.model.js +4 -0
  240. package/models/app-setting.model.js.map +1 -0
  241. package/{src/models/app-status.model.ts → models/app-status.model.d.ts} +2 -3
  242. package/models/app-status.model.js +4 -0
  243. package/models/app-status.model.js.map +1 -0
  244. package/{src/models/billing-logged-in-users.model.ts → models/billing-logged-in-users.model.d.ts} +4 -5
  245. package/models/billing-logged-in-users.model.js +4 -0
  246. package/models/billing-logged-in-users.model.js.map +1 -0
  247. package/models/collection-document.model.d.ts +21 -0
  248. package/models/collection-document.model.js +4 -0
  249. package/models/collection-document.model.js.map +1 -0
  250. package/models/communication-metric.model.d.ts +20 -0
  251. package/models/communication-metric.model.js +4 -0
  252. package/models/communication-metric.model.js.map +1 -0
  253. package/{src/models/counter.model.ts → models/counter.model.d.ts} +3 -4
  254. package/models/counter.model.js +4 -0
  255. package/models/counter.model.js.map +1 -0
  256. package/models/cron-job-history.model.d.ts +15 -0
  257. package/models/cron-job-history.model.js +4 -0
  258. package/models/cron-job-history.model.js.map +1 -0
  259. package/models/cron-job.model.d.ts +14 -0
  260. package/models/cron-job.model.js +4 -0
  261. package/models/cron-job.model.js.map +1 -0
  262. package/models/customer-notification.model.d.ts +26 -0
  263. package/models/customer-notification.model.js +4 -0
  264. package/models/customer-notification.model.js.map +1 -0
  265. package/models/customer-portal-password.model.d.ts +11 -0
  266. package/models/customer-portal-password.model.js +4 -0
  267. package/models/customer-portal-password.model.js.map +1 -0
  268. package/models/dialog.model.d.ts +23 -0
  269. package/models/dialog.model.js +4 -0
  270. package/models/dialog.model.js.map +1 -0
  271. package/models/email-history.model.d.ts +30 -0
  272. package/{src/models/email-history.model.ts → models/email-history.model.js} +4 -34
  273. package/models/email-history.model.js.map +1 -0
  274. package/{src/models/email-verified.model.ts → models/email-verified.model.d.ts} +5 -6
  275. package/models/email-verified.model.js +4 -0
  276. package/models/email-verified.model.js.map +1 -0
  277. package/{src/models/file.model.ts → models/file.model.d.ts} +7 -8
  278. package/models/file.model.js +4 -0
  279. package/models/file.model.js.map +1 -0
  280. package/{src/models/flag-update.model.ts → models/flag-update.model.d.ts} +3 -4
  281. package/models/flag-update.model.js +4 -0
  282. package/models/flag-update.model.js.map +1 -0
  283. package/{src/models/flag.model.ts → models/flag.model.d.ts} +3 -4
  284. package/models/flag.model.js +4 -0
  285. package/models/flag.model.js.map +1 -0
  286. package/models/log-method-latency.model.d.ts +10 -0
  287. package/models/log-method-latency.model.js +4 -0
  288. package/models/log-method-latency.model.js.map +1 -0
  289. package/{src/models/log-subscription.model.ts → models/log-subscription.model.d.ts} +9 -11
  290. package/models/log-subscription.model.js +4 -0
  291. package/models/log-subscription.model.js.map +1 -0
  292. package/models/log.model.d.ts +17 -0
  293. package/models/log.model.js +4 -0
  294. package/models/log.model.js.map +1 -0
  295. package/{src/models/logged-in-users.model.ts → models/logged-in-users.model.d.ts} +5 -6
  296. package/models/logged-in-users.model.js +4 -0
  297. package/models/logged-in-users.model.js.map +1 -0
  298. package/{src/models/method-response.model.ts → models/method-response.model.d.ts} +6 -7
  299. package/models/method-response.model.js +4 -0
  300. package/models/method-response.model.js.map +1 -0
  301. package/models/method.model.d.ts +24 -0
  302. package/models/method.model.js +4 -0
  303. package/models/method.model.js.map +1 -0
  304. package/{src/models/monitor-cpu.model.ts → models/monitor-cpu.model.d.ts} +7 -9
  305. package/models/monitor-cpu.model.js +4 -0
  306. package/models/monitor-cpu.model.js.map +1 -0
  307. package/models/monitor-function.model.d.ts +14 -0
  308. package/models/monitor-function.model.js +4 -0
  309. package/models/monitor-function.model.js.map +1 -0
  310. package/models/monitor-memory.model.d.ts +15 -0
  311. package/models/monitor-memory.model.js +4 -0
  312. package/models/monitor-memory.model.js.map +1 -0
  313. package/models/monitor-mongo.model.d.ts +13 -0
  314. package/models/monitor-mongo.model.js +4 -0
  315. package/models/monitor-mongo.model.js.map +1 -0
  316. package/{src/models/notification.model.ts → models/notification.model.d.ts} +4 -6
  317. package/models/notification.model.js +4 -0
  318. package/models/notification.model.js.map +1 -0
  319. package/models/openai-usage-ledger.model.d.ts +15 -0
  320. package/models/openai-usage-ledger.model.js +4 -0
  321. package/models/openai-usage-ledger.model.js.map +1 -0
  322. package/models/pagination.model.d.ts +11 -0
  323. package/models/pagination.model.js +28 -0
  324. package/models/pagination.model.js.map +1 -0
  325. package/models/permission.model.d.ts +12 -0
  326. package/models/permission.model.js +4 -0
  327. package/models/permission.model.js.map +1 -0
  328. package/models/report-builder-dashboard-builder.model.d.ts +25 -0
  329. package/models/report-builder-dashboard-builder.model.js +4 -0
  330. package/models/report-builder-dashboard-builder.model.js.map +1 -0
  331. package/models/report-builder-library.model.d.ts +17 -0
  332. package/models/report-builder-library.model.js +4 -0
  333. package/models/report-builder-library.model.js.map +1 -0
  334. package/models/report-builder-report.model.d.ts +120 -0
  335. package/models/report-builder-report.model.js +4 -0
  336. package/models/report-builder-report.model.js.map +1 -0
  337. package/models/report-builder.model.d.ts +61 -0
  338. package/models/report-builder.model.js +4 -0
  339. package/models/report-builder.model.js.map +1 -0
  340. package/models/select-data-label.model.d.ts +9 -0
  341. package/models/select-data-label.model.js +4 -0
  342. package/models/select-data-label.model.js.map +1 -0
  343. package/models/server-message.model.d.ts +32 -0
  344. package/models/server-message.model.js +4 -0
  345. package/models/server-message.model.js.map +1 -0
  346. package/models/slow-query-report.model.d.ts +23 -0
  347. package/models/slow-query-report.model.js +4 -0
  348. package/models/slow-query-report.model.js.map +1 -0
  349. package/models/subscription.model.d.ts +31 -0
  350. package/models/subscription.model.js +4 -0
  351. package/models/subscription.model.js.map +1 -0
  352. package/models/support-ticket.model.d.ts +86 -0
  353. package/models/support-ticket.model.js +4 -0
  354. package/models/support-ticket.model.js.map +1 -0
  355. package/models/user-group.model.d.ts +20 -0
  356. package/models/user-group.model.js +4 -0
  357. package/models/user-group.model.js.map +1 -0
  358. package/{src/models/user-guide.model.ts → models/user-guide.model.d.ts} +4 -5
  359. package/models/user-guide.model.js +4 -0
  360. package/models/user-guide.model.js.map +1 -0
  361. package/models/user.model.d.ts +84 -0
  362. package/models/user.model.js +4 -0
  363. package/models/user.model.js.map +1 -0
  364. package/package.json +1 -1
  365. package/private/images/ResolveIO.png +0 -0
  366. package/public_api.js +107 -0
  367. package/public_api.js.map +1 -0
  368. package/publications/ai-terminal.d.ts +1 -0
  369. package/publications/ai-terminal.js +122 -0
  370. package/publications/ai-terminal.js.map +1 -0
  371. package/publications/app-settings.d.ts +2 -0
  372. package/publications/app-settings.js +28 -0
  373. package/publications/app-settings.js.map +1 -0
  374. package/publications/app-status.d.ts +2 -0
  375. package/publications/app-status.js +16 -0
  376. package/publications/app-status.js.map +1 -0
  377. package/publications/cron-jobs.d.ts +2 -0
  378. package/publications/cron-jobs.js +32 -0
  379. package/publications/cron-jobs.js.map +1 -0
  380. package/publications/customer-notifications.d.ts +2 -0
  381. package/publications/customer-notifications.js +161 -0
  382. package/publications/customer-notifications.js.map +1 -0
  383. package/publications/files.d.ts +2 -0
  384. package/publications/files.js +36 -0
  385. package/publications/files.js.map +1 -0
  386. package/publications/flags-update.d.ts +2 -0
  387. package/publications/flags-update.js +22 -0
  388. package/publications/flags-update.js.map +1 -0
  389. package/publications/flags.d.ts +2 -0
  390. package/publications/flags.js +22 -0
  391. package/publications/flags.js.map +1 -0
  392. package/publications/logs.d.ts +2 -0
  393. package/publications/logs.js +164 -0
  394. package/publications/logs.js.map +1 -0
  395. package/publications/notifications.d.ts +2 -0
  396. package/publications/notifications.js +16 -0
  397. package/publications/notifications.js.map +1 -0
  398. package/publications/report-builder-dashboard-builders.d.ts +2 -0
  399. package/publications/report-builder-dashboard-builders.js +42 -0
  400. package/publications/report-builder-dashboard-builders.js.map +1 -0
  401. package/publications/report-builder-libraries.d.ts +2 -0
  402. package/publications/report-builder-libraries.js +90 -0
  403. package/publications/report-builder-libraries.js.map +1 -0
  404. package/publications/report-builder-reports.d.ts +2 -0
  405. package/publications/report-builder-reports.js +50 -0
  406. package/publications/report-builder-reports.js.map +1 -0
  407. package/publications/super-admin.d.ts +2 -0
  408. package/publications/super-admin.js +16 -0
  409. package/publications/super-admin.js.map +1 -0
  410. package/publications/user-groups.d.ts +1 -0
  411. package/publications/user-groups.js +16 -0
  412. package/publications/user-groups.js.map +1 -0
  413. package/publications/user-guides.d.ts +1 -0
  414. package/publications/user-guides.js +16 -0
  415. package/publications/user-guides.js.map +1 -0
  416. package/resolveio-server-app.d.ts +70 -0
  417. package/resolveio-server-app.js +801 -0
  418. package/resolveio-server-app.js.map +1 -0
  419. package/server-app.d.ts +167 -0
  420. package/server-app.js +2784 -0
  421. package/server-app.js.map +1 -0
  422. package/services/codex-client.d.ts +119 -0
  423. package/services/codex-client.js +1470 -0
  424. package/services/codex-client.js.map +1 -0
  425. package/services/openai-client.d.ts +46 -0
  426. package/services/openai-client.js +318 -0
  427. package/services/openai-client.js.map +1 -0
  428. package/types/error-report.d.ts +25 -0
  429. package/types/error-report.js +4 -0
  430. package/types/error-report.js.map +1 -0
  431. package/types/slow-query-report.d.ts +27 -0
  432. package/types/slow-query-report.js +6 -0
  433. package/types/slow-query-report.js.map +1 -0
  434. package/util/common.d.ts +31 -0
  435. package/util/common.js +683 -0
  436. package/util/common.js.map +1 -0
  437. package/util/customer-portal-password.d.ts +13 -0
  438. package/util/customer-portal-password.js +209 -0
  439. package/util/customer-portal-password.js.map +1 -0
  440. package/util/error-reporter.d.ts +52 -0
  441. package/util/error-reporter.js +326 -0
  442. package/util/error-reporter.js.map +1 -0
  443. package/util/error-tracking.d.ts +13 -0
  444. package/util/error-tracking.js +120 -0
  445. package/util/error-tracking.js.map +1 -0
  446. package/util/report-builder-unwinds.d.ts +15 -0
  447. package/util/report-builder-unwinds.js +156 -0
  448. package/util/report-builder-unwinds.js.map +1 -0
  449. package/util/schema-report-builder.d.ts +6 -0
  450. package/util/schema-report-builder.js +481 -0
  451. package/util/schema-report-builder.js.map +1 -0
  452. package/util/slow-query-reporter.d.ts +28 -0
  453. package/util/slow-query-reporter.js +226 -0
  454. package/util/slow-query-reporter.js.map +1 -0
  455. package/util/subscription-dependency-context.d.ts +34 -0
  456. package/util/subscription-dependency-context.js +1283 -0
  457. package/util/subscription-dependency-context.js.map +1 -0
  458. package/util/tokenizer.d.ts +5 -0
  459. package/util/tokenizer.js +41 -0
  460. package/util/tokenizer.js.map +1 -0
  461. package/workers/codex-runner.worker.d.ts +1 -0
  462. package/workers/codex-runner.worker.js +192 -0
  463. package/workers/codex-runner.worker.js.map +1 -0
  464. package/.github/workflows/ai-assistant-nightly-eval.yml +0 -224
  465. package/.github/workflows/ai-assistant-pr-guardrails.yml +0 -60
  466. package/.nodemon.json +0 -5
  467. package/.vscode/settings.json +0 -21
  468. package/AGENTS.md +0 -179
  469. package/README.md +0 -22
  470. package/build_package.sh +0 -5
  471. package/compileDTS.pl +0 -64
  472. package/docs/ai-assistant-nightly-eval.md +0 -65
  473. package/docs/ai-assistant-preflight-checklist.md +0 -23
  474. package/docs/ai-assistant-report-builder-bridge-playbook.md +0 -115
  475. package/eslint-plugin-custom/index.js +0 -7
  476. package/eslint-plugin-custom/rules/no-filter-zero-index.js +0 -44
  477. package/eslint.config.js +0 -103
  478. package/gulpfile.js +0 -216
  479. package/methodAndPublicationListGenerator.py +0 -319
  480. package/mongodbensurers.js +0 -2
  481. package/mongostop.js +0 -3
  482. package/settings.development.json +0 -25
  483. package/settings.development.redacted.json +0 -25
  484. package/src/.env +0 -12
  485. package/src/ai/assistant-core-heuristics.ts +0 -577
  486. package/src/client-server-app.ts +0 -12
  487. package/src/collections/ai-terminal-conversation.collection.ts +0 -91
  488. package/src/collections/ai-terminal-issue-report.collection.ts +0 -99
  489. package/src/collections/ai-terminal-message.collection.ts +0 -77
  490. package/src/collections/app-setting.collection.ts +0 -104
  491. package/src/collections/app-status.collection.ts +0 -58
  492. package/src/collections/communication-metric.collection.ts +0 -84
  493. package/src/collections/counter.collection.ts +0 -56
  494. package/src/collections/cron-job-history.collection.ts +0 -94
  495. package/src/collections/cron-job.collection.ts +0 -92
  496. package/src/collections/customer-notification.collection.ts +0 -131
  497. package/src/collections/customer-portal-password.collection.ts +0 -76
  498. package/src/collections/email-history.collection.ts +0 -121
  499. package/src/collections/email-verified.collection.ts +0 -61
  500. package/src/collections/file.collection.ts +0 -74
  501. package/src/collections/flag-update.collection.ts +0 -57
  502. package/src/collections/flag.collection.ts +0 -57
  503. package/src/collections/log-method-latency.collection.ts +0 -77
  504. package/src/collections/log-subscription.collection.ts +0 -80
  505. package/src/collections/log.collection.ts +0 -93
  506. package/src/collections/logged-in-users.collection.ts +0 -67
  507. package/src/collections/monitor-cpu.collection.ts +0 -65
  508. package/src/collections/monitor-function.collection.ts +0 -74
  509. package/src/collections/monitor-memory.collection.ts +0 -77
  510. package/src/collections/monitor-mongo.collection.ts +0 -71
  511. package/src/collections/notification.collection.ts +0 -57
  512. package/src/collections/openai-usage-ledger.collection.ts +0 -77
  513. package/src/collections/report-builder-dashboard-builder.collection.ts +0 -109
  514. package/src/collections/report-builder-library.collection.ts +0 -89
  515. package/src/collections/report-builder-report.collection.ts +0 -180
  516. package/src/collections/user-group.collection.ts +0 -89
  517. package/src/collections/user-guide.collection.ts +0 -57
  518. package/src/collections/user.collection.ts +0 -181
  519. package/src/cron/cron.ts +0 -117
  520. package/src/fixtures/cron-jobs.ts +0 -95
  521. package/src/fixtures/init.ts +0 -35
  522. package/src/http/auth.ts +0 -764
  523. package/src/http/health.ts +0 -7
  524. package/src/http/home.ts +0 -90
  525. package/src/http/slow-query-publication.ts +0 -49
  526. package/src/index.ts +0 -1
  527. package/src/managers/communication-metric.manager.ts +0 -82
  528. package/src/managers/cron.manager.ts +0 -333
  529. package/src/managers/customer-notification-content.manager.ts +0 -236
  530. package/src/managers/diagnostic-manager-bootstrap.ts +0 -165
  531. package/src/managers/error-auto-fix.manager.ts +0 -2767
  532. package/src/managers/local-log.manager.ts +0 -113
  533. package/src/managers/method.manager.ts +0 -1557
  534. package/src/managers/mongo.manager.ts +0 -4566
  535. package/src/managers/monitor.manager.ts +0 -489
  536. package/src/managers/openai-usage-ledger.manager.ts +0 -116
  537. package/src/managers/slow-query-verifier.manager.ts +0 -3590
  538. package/src/managers/slow-query.manager.ts +0 -519
  539. package/src/managers/subscription.manager.ts +0 -3120
  540. package/src/managers/websocket.manager.ts +0 -746
  541. package/src/managers/worker-dispatcher.manager.ts +0 -1318
  542. package/src/managers/worker-server.manager.ts +0 -468
  543. package/src/methods/accounts.ts +0 -532
  544. package/src/methods/ai-terminal.ts +0 -25505
  545. package/src/methods/app-settings.ts +0 -114
  546. package/src/methods/aws.ts +0 -646
  547. package/src/methods/collections.ts +0 -544
  548. package/src/methods/counters.ts +0 -67
  549. package/src/methods/cron-jobs.ts +0 -2610
  550. package/src/methods/customer-notifications.ts +0 -458
  551. package/src/methods/diagnostics.ts +0 -447
  552. package/src/methods/flag-updates.ts +0 -7
  553. package/src/methods/flags.ts +0 -7
  554. package/src/methods/logs.ts +0 -656
  555. package/src/methods/mongo-explorer.ts +0 -1883
  556. package/src/methods/monitor.ts +0 -540
  557. package/src/methods/pdf.ts +0 -1210
  558. package/src/methods/publications.ts +0 -128
  559. package/src/methods/report-builder.ts +0 -3305
  560. package/src/methods/support.ts +0 -210
  561. package/src/models/ai-terminal-conversation.model.ts +0 -19
  562. package/src/models/ai-terminal-issue-report.model.ts +0 -21
  563. package/src/models/ai-terminal-message.model.ts +0 -24
  564. package/src/models/app-setting.model.ts +0 -17
  565. package/src/models/collection-document.model.ts +0 -24
  566. package/src/models/communication-metric.model.ts +0 -23
  567. package/src/models/cron-job-history.model.ts +0 -16
  568. package/src/models/cron-job.model.ts +0 -15
  569. package/src/models/customer-notification.model.ts +0 -28
  570. package/src/models/customer-portal-password.model.ts +0 -12
  571. package/src/models/dialog.model.ts +0 -25
  572. package/src/models/log-method-latency.model.ts +0 -11
  573. package/src/models/log.model.ts +0 -19
  574. package/src/models/method.model.ts +0 -23
  575. package/src/models/monitor-function.model.ts +0 -16
  576. package/src/models/monitor-memory.model.ts +0 -17
  577. package/src/models/monitor-mongo.model.ts +0 -15
  578. package/src/models/openai-usage-ledger.model.ts +0 -16
  579. package/src/models/pagination.model.ts +0 -35
  580. package/src/models/permission.model.ts +0 -14
  581. package/src/models/report-builder-dashboard-builder.model.ts +0 -29
  582. package/src/models/report-builder-library.model.ts +0 -20
  583. package/src/models/report-builder-report.model.ts +0 -135
  584. package/src/models/report-builder.model.ts +0 -68
  585. package/src/models/select-data-label.model.ts +0 -9
  586. package/src/models/server-message.model.ts +0 -31
  587. package/src/models/slow-query-report.model.ts +0 -23
  588. package/src/models/subscription.model.ts +0 -73
  589. package/src/models/support-ticket.model.ts +0 -96
  590. package/src/models/user-group.model.ts +0 -24
  591. package/src/models/user.model.ts +0 -96
  592. package/src/private/images/ResolveIO.png +0 -0
  593. package/src/publications/ai-terminal.ts +0 -73
  594. package/src/publications/app-settings.ts +0 -25
  595. package/src/publications/app-status.ts +0 -13
  596. package/src/publications/cron-jobs.ts +0 -29
  597. package/src/publications/customer-notifications.ts +0 -101
  598. package/src/publications/files.ts +0 -33
  599. package/src/publications/flags-update.ts +0 -19
  600. package/src/publications/flags.ts +0 -19
  601. package/src/publications/logs.ts +0 -163
  602. package/src/publications/notifications.ts +0 -13
  603. package/src/publications/report-builder-dashboard-builders.ts +0 -39
  604. package/src/publications/report-builder-libraries.ts +0 -41
  605. package/src/publications/report-builder-reports.ts +0 -47
  606. package/src/publications/super-admin.ts +0 -13
  607. package/src/publications/user-groups.ts +0 -12
  608. package/src/publications/user-guides.ts +0 -12
  609. package/src/resolveio-server-app.ts +0 -617
  610. package/src/server-app.ts +0 -2616
  611. package/src/services/codex-client.ts +0 -1117
  612. package/src/services/openai-client.ts +0 -265
  613. package/src/types/error-report.ts +0 -26
  614. package/src/types/js-tiktoken.d.ts +0 -11
  615. package/src/types/slow-query-report.ts +0 -28
  616. package/src/util/common.ts +0 -649
  617. package/src/util/customer-portal-password.ts +0 -183
  618. package/src/util/error-reporter.ts +0 -332
  619. package/src/util/error-tracking.ts +0 -79
  620. package/src/util/report-builder-unwinds.ts +0 -180
  621. package/src/util/schema-report-builder.ts +0 -448
  622. package/src/util/slow-query-reporter.ts +0 -216
  623. package/src/util/subscription-dependency-context.ts +0 -1096
  624. package/src/util/tokenizer.ts +0 -38
  625. package/src/workers/codex-runner.worker.ts +0 -142
  626. package/start_server.sh +0 -5
  627. package/tests/ai-assistant-corpus-build.ts +0 -484
  628. package/tests/ai-assistant-corpus-replay-e2e.ts +0 -773
  629. package/tests/ai-assistant-data-parity-e2e.ts +0 -2018
  630. package/tests/ai-assistant-eval-triage.ts +0 -831
  631. package/tests/ai-assistant-openai-e2e.ts +0 -1061
  632. package/tests/ai-assistant-openai-git-e2e.ts +0 -155
  633. package/tests/ai-assistant-preflight-matrix.ts +0 -215
  634. package/tests/ai-assistant-routing-eval.test.ts +0 -560
  635. package/tests/ai-assistant-snf-live-eval.ts +0 -921
  636. package/tests/ai-assistant-utils.test.ts +0 -2165
  637. package/tests/error-reporter.test.ts +0 -145
  638. package/tests/report-builder-linking.test.ts +0 -79
  639. package/tests/subscription-connect-race.test.ts +0 -157
  640. package/tests/subscription-dependency-context.test.ts +0 -324
  641. package/tests/subscription-manager-collection-tracking.test.ts +0 -86
  642. package/tests/subscription-manager-invalidation.test.ts +0 -85
  643. package/tsconfig.json +0 -34
  644. /package/{src/private → private}/email-templates/enrollment.html +0 -0
  645. /package/{src/private → private}/email-templates/forgot-password.html +0 -0
  646. /package/{src/private → private}/email-templates/support-ticket-deleted.html +0 -0
  647. /package/{src/private → private}/email-templates/support-ticket-modified.html +0 -0
  648. /package/{src/private → private}/email-templates/support-ticket.html +0 -0
  649. /package/{src/public_api.ts → public_api.d.ts} +0 -0
@@ -1,1883 +0,0 @@
1
- import SimpleSchema from 'simpl-schema';
2
- import { Db } from 'mongodb';
3
- import { Users } from '../collections/user.collection';
4
- import { MethodManager } from '../managers/method.manager';
5
- import { recordOpenAIUsage } from '../managers/openai-usage-ledger.manager';
6
- import { ResolveIOServer } from '../resolveio-server-app';
7
- import { CodexClient } from '../services/codex-client';
8
- import { objectIdHexString, round } from '../util/common';
9
- import { countChatTokens, countTokens } from '../util/tokenizer';
10
-
11
- const DEFAULT_LIMIT = 100;
12
- const MAX_LIMIT = 2000;
13
- const ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
14
- const MAX_REVIEW_STRING_LENGTH = 500;
15
- const MAX_REVIEW_ARRAY_ITEMS = 10;
16
- const MAX_REVIEW_OBJECT_KEYS = 40;
17
- const MAX_REVIEW_DEPTH = 4;
18
- const MAX_REVIEW_LIST_ITEMS = 6;
19
- const MAX_REVIEW_CHANGED_FIELDS = 60;
20
- const DEFAULT_RISK_REVIEW_TIMEOUT_MS = 30000;
21
- const DEFAULT_RISK_REVIEW_MAX_TOKENS = 700;
22
- const DEFAULT_RISK_REVIEW_MODEL = 'gpt-5.3-codex';
23
- const SENSITIVE_REVIEW_FIELD_REGEX = /(password|secret|token|api[_-]?key|salt|hash|email|phone|address|ssn|services|roles)/i;
24
- const DEFAULT_AI_SUGGEST_TIMEOUT_MS = 60000;
25
- const DEFAULT_AI_SUGGEST_MAX_TOKENS = 1000;
26
- const DEFAULT_AI_SUGGEST_MODEL = 'gpt-5.3-codex';
27
- const DEFAULT_AI_SUGGEST_FALLBACK_MODEL = 'gpt-5.2-codex';
28
- const MAX_AI_SUGGEST_FIELDS = 700;
29
- const MAX_AI_SUGGEST_COLLECTIONS = 800;
30
- const MAX_AI_SUGGEST_RESULTS = 500;
31
- const RESTRICTED_AGGREGATE_STAGES = new Set(['$out', '$merge']);
32
-
33
- type ExplorerFindOptions = {
34
- projection?: Record<string, number>;
35
- sort?: Record<string, any>;
36
- limit?: number;
37
- skip?: number;
38
- includeTotal?: boolean;
39
- };
40
-
41
- type ExplorerMode = 'resolveio' | 'aicoder';
42
-
43
- type MongoExplorerDeleteImpactCollection = {
44
- collection: string;
45
- references: number;
46
- sample_ids: string[];
47
- };
48
-
49
- type MongoExplorerDeleteImpact = {
50
- has_references: boolean;
51
- unresolved: boolean;
52
- collections: MongoExplorerDeleteImpactCollection[];
53
- };
54
-
55
- type MongoExplorerRiskOperation = 'insert' | 'replace' | 'delete' | 'command';
56
- type MongoExplorerRiskLevel = 'low' | 'medium' | 'high' | 'critical';
57
- type MongoExplorerRiskReviewStatus = 'ok' | 'fallback' | 'disabled';
58
-
59
- type MongoExplorerRiskReview = {
60
- operation: MongoExplorerRiskOperation;
61
- risk_level: MongoExplorerRiskLevel;
62
- should_block: boolean;
63
- summary: string;
64
- reasons: string[];
65
- suggested_checks: string[];
66
- confidence: number;
67
- model: string;
68
- request_id: string;
69
- review_status: MongoExplorerRiskReviewStatus;
70
- reviewed_at: string;
71
- };
72
-
73
- type MongoExplorerRiskReviewInput = {
74
- database: string;
75
- collection: string;
76
- operation: MongoExplorerRiskOperation;
77
- mode: ExplorerMode;
78
- before_document?: any;
79
- after_document?: any;
80
- delete_impact?: MongoExplorerDeleteImpact;
81
- };
82
-
83
- type MongoExplorerAiAction = 'find' | 'aggregate';
84
-
85
- type MongoExplorerAiPayload = {
86
- prompt?: string;
87
- database?: string;
88
- selected_collection?: string;
89
- available_collections?: Array<{ name?: string; collection?: string; type?: string }>;
90
- available_fields?: Array<{ path?: string; label?: string; type?: string; collection?: string }>;
91
- permission_view?: string;
92
- mode?: string;
93
- id_client?: string;
94
- max_results?: number;
95
- };
96
-
97
- type MongoExplorerAiField = {
98
- path: string;
99
- label: string;
100
- type: string;
101
- collection: string;
102
- };
103
-
104
- type MongoExplorerAiPlan = {
105
- action: MongoExplorerAiAction;
106
- collection: string;
107
- query?: Record<string, any>;
108
- pipeline?: any[];
109
- options?: Record<string, any>;
110
- documents?: any[];
111
- total?: number | null;
112
- notes?: string;
113
- };
114
-
115
- function parseMongoExplorerWriteUsers(): string[] {
116
- const raw = typeof process.env.MONGO_EXPLORER_WRITE_USERS === 'string' ? process.env.MONGO_EXPLORER_WRITE_USERS.trim() : '';
117
- if (!raw) {
118
- return [];
119
- }
120
-
121
- try {
122
- const parsed = JSON.parse(raw);
123
- if (Array.isArray(parsed)) {
124
- return parsed.map(value => String(value)).filter(value => value.trim().length);
125
- }
126
- if (typeof parsed === 'string') {
127
- return [parsed.trim()].filter(Boolean);
128
- }
129
- }
130
- catch {
131
- // Fall back to comma-separated list.
132
- }
133
-
134
- return raw
135
- .split(',')
136
- .map(value => value.trim())
137
- .filter(Boolean);
138
- }
139
-
140
- function normalizeExplorerMode(mode?: string): ExplorerMode {
141
- const normalizedMode = String(mode || '').trim().toLowerCase();
142
- if (normalizedMode === 'resolveio') {
143
- return 'resolveio';
144
- }
145
- return 'aicoder';
146
- }
147
-
148
- function allowUnschemaizedWrites(): boolean {
149
- return process.env.MONGO_EXPLORER_ALLOW_UNSCHEMATIZED_WRITE === 'true';
150
- }
151
-
152
- function resolveDatabaseName(database?: string): string {
153
- const defaultDb = ResolveIOServer.getServerConfig()?.DATABASE || '';
154
- const dbName = typeof database === 'string' && database.trim().length ? database.trim() : defaultDb;
155
-
156
- if (!dbName) {
157
- throw new Error('Mongo Explorer: Database is required');
158
- }
159
-
160
- const allowedDatabases = ResolveIOServer.getMongoManager()?.getWatchedDatabases() || [];
161
- if (allowedDatabases.length && !allowedDatabases.includes(dbName)) {
162
- throw new Error('Mongo Explorer: Database access denied');
163
- }
164
-
165
- return dbName;
166
- }
167
-
168
- function resolveDatabase(database?: string): Db {
169
- const dbName = resolveDatabaseName(database);
170
- return ResolveIOServer.getMongoConnection().db(dbName);
171
- }
172
-
173
- function resolveCollectionHandle(database: string, collection: string) {
174
- const mainDb = ResolveIOServer.getServerConfig()?.DATABASE || '';
175
- const isMainDb = database === mainDb;
176
- const managerCollection = isMainDb ? ResolveIOServer.getMongoManager()?.collection(collection) : null;
177
- const db = ResolveIOServer.getMongoConnection().db(database);
178
-
179
- return {
180
- managerCollection,
181
- dbCollection: db.collection(collection)
182
- };
183
- }
184
-
185
- function getSchemaDefinition(collectionRef: any): Record<string, any> {
186
- if (!collectionRef || !collectionRef.simplschema || typeof collectionRef.simplschema.schema !== 'function') {
187
- return {};
188
- }
189
-
190
- const schema = collectionRef.simplschema.schema();
191
- return schema && typeof schema === 'object' ? schema : {};
192
- }
193
-
194
- function getSchemaTypeName(definition: any): string {
195
- const typeDefs = definition?.type?.definitions;
196
- if (!Array.isArray(typeDefs) || !typeDefs.length) {
197
- return 'Any';
198
- }
199
-
200
- const firstType = typeDefs[0]?.type;
201
- if (!firstType) {
202
- return 'Any';
203
- }
204
-
205
- if (firstType === String) {
206
- return 'String';
207
- }
208
- if (firstType === Number) {
209
- return 'Number';
210
- }
211
- if (firstType === Boolean) {
212
- return 'Boolean';
213
- }
214
- if (firstType === Date) {
215
- return 'Date';
216
- }
217
- if (firstType === Object) {
218
- return 'Object';
219
- }
220
- if (firstType === Array) {
221
- return 'Array';
222
- }
223
-
224
- const typeName = firstType.name || String(firstType);
225
- if (typeName === 'Integer') {
226
- return 'Number';
227
- }
228
- return typeName;
229
- }
230
-
231
- function toLabel(path: string): string {
232
- const last = path.split('.').pop() || path;
233
- return last
234
- .replace(/\$/g, '')
235
- .replace(/_/g, ' ')
236
- .replace(/\s+/g, ' ')
237
- .trim();
238
- }
239
-
240
- function isProtectedFieldSegment(segment: string): boolean {
241
- if (!segment) {
242
- return false;
243
- }
244
-
245
- if (segment === '_id') {
246
- return true;
247
- }
248
-
249
- const normalizedSegment = segment.replace(/\[\d+\]/g, '');
250
- return normalizedSegment.toLowerCase().startsWith('id_');
251
- }
252
-
253
- function isProtectedFieldPath(path: string): boolean {
254
- const segments = String(path || '').split('.').filter(Boolean);
255
- return segments.some(segment => isProtectedFieldSegment(segment));
256
- }
257
-
258
- function safeStringify(value: unknown): string {
259
- try {
260
- return JSON.stringify(value);
261
- }
262
- catch {
263
- return String(value);
264
- }
265
- }
266
-
267
- function collectProtectedFieldPaths(value: any, prefix = '', out: Record<string, any> = {}): Record<string, any> {
268
- if (Array.isArray(value)) {
269
- value.forEach((item, index) => {
270
- const nextPrefix = prefix ? `${prefix}[${index}]` : `[${index}]`;
271
- collectProtectedFieldPaths(item, nextPrefix, out);
272
- });
273
- return out;
274
- }
275
-
276
- if (!value || typeof value !== 'object') {
277
- return out;
278
- }
279
-
280
- Object.keys(value).forEach((key) => {
281
- const nextPrefix = prefix ? `${prefix}.${key}` : key;
282
- if (isProtectedFieldSegment(key)) {
283
- out[nextPrefix] = value[key];
284
- }
285
- collectProtectedFieldPaths(value[key], nextPrefix, out);
286
- });
287
-
288
- return out;
289
- }
290
-
291
- function ensureProtectedFieldsUnchanged(originalDoc: any, updatedDoc: any) {
292
- const originalProtected = collectProtectedFieldPaths(originalDoc || {});
293
- const updatedProtected = collectProtectedFieldPaths(updatedDoc || {});
294
- const violations: string[] = [];
295
-
296
- Object.keys(originalProtected).forEach((path) => {
297
- if (!Object.prototype.hasOwnProperty.call(updatedProtected, path)) {
298
- violations.push(path);
299
- return;
300
- }
301
-
302
- const originalValue = safeStringify(originalProtected[path]);
303
- const updatedValue = safeStringify(updatedProtected[path]);
304
- if (originalValue !== updatedValue) {
305
- violations.push(path);
306
- }
307
- });
308
-
309
- Object.keys(updatedProtected).forEach((path) => {
310
- if (!Object.prototype.hasOwnProperty.call(originalProtected, path)) {
311
- violations.push(path);
312
- }
313
- });
314
-
315
- if (violations.length) {
316
- const preview = violations.slice(0, 4).join(', ');
317
- throw new Error(`Mongo Explorer: Protected fields cannot be edited (${preview}${violations.length > 4 ? ', ...' : ''})`);
318
- }
319
- }
320
-
321
- function coerceDateValue(value: unknown): unknown {
322
- if (value instanceof Date) {
323
- return value;
324
- }
325
-
326
- if (typeof value !== 'string' || !ISO_DATE_REGEX.test(value)) {
327
- return value;
328
- }
329
-
330
- const parsed = new Date(value);
331
- return Number.isNaN(parsed.getTime()) ? value : parsed;
332
- }
333
-
334
- function coerceDatePath(target: any, segments: string[]) {
335
- if (!target || !segments.length) {
336
- return;
337
- }
338
-
339
- const [segment, ...rest] = segments;
340
-
341
- if (segment === '$') {
342
- if (Array.isArray(target)) {
343
- target.forEach(item => coerceDatePath(item, rest));
344
- }
345
- return;
346
- }
347
-
348
- if (!Object.prototype.hasOwnProperty.call(target, segment)) {
349
- return;
350
- }
351
-
352
- if (rest.length === 0) {
353
- const updatedValue = coerceDateValue(target[segment]);
354
- if (updatedValue !== target[segment]) {
355
- target[segment] = updatedValue;
356
- }
357
- return;
358
- }
359
-
360
- coerceDatePath(target[segment], rest);
361
- }
362
-
363
- function coerceDateFields(collectionRef: any, doc: any) {
364
- if (!collectionRef || !collectionRef.simplschema || !doc) {
365
- return;
366
- }
367
-
368
- const schema = getSchemaDefinition(collectionRef);
369
- Object.keys(schema).forEach((schemaKey) => {
370
- const definition = schema[schemaKey];
371
- const typeDefs = definition?.type?.definitions;
372
- if (!Array.isArray(typeDefs) || !typeDefs.some(typeDef => typeDef.type === Date)) {
373
- return;
374
- }
375
-
376
- coerceDatePath(doc, schemaKey.split('.'));
377
- });
378
- }
379
-
380
- function normalizeFindOptions(options?: ExplorerFindOptions) {
381
- const normalized = options || {};
382
- const projection = normalized.projection && Object.keys(normalized.projection).length ? normalized.projection : undefined;
383
- const sort = normalized.sort && Object.keys(normalized.sort).length ? normalized.sort : undefined;
384
- const limit = typeof normalized.limit === 'number' ? Math.min(Math.max(normalized.limit, 0), MAX_LIMIT) : DEFAULT_LIMIT;
385
- const skip = typeof normalized.skip === 'number' ? Math.max(normalized.skip, 0) : 0;
386
-
387
- return {
388
- findOptions: {
389
- projection,
390
- sort,
391
- limit,
392
- skip
393
- },
394
- includeTotal: normalized.includeTotal === true
395
- };
396
- }
397
-
398
- function userHasView(user, view: string): boolean {
399
- if (!user || !view) {
400
- return false;
401
- }
402
-
403
- if (user.roles?.super_admin) {
404
- return true;
405
- }
406
-
407
- const groups = Array.isArray(user.roles?.groups) ? user.roles.groups : [];
408
- const miscs = Array.isArray(user.roles?.miscs) ? user.roles.miscs : [];
409
-
410
- if (groups.some(group => Array.isArray(group.views) && group.views.some(v => v.startsWith(view)))) {
411
- return true;
412
- }
413
-
414
- if (miscs.some(v => v.startsWith(view))) {
415
- return true;
416
- }
417
-
418
- if (groups.some(group => group.name === view)) {
419
- return true;
420
- }
421
-
422
- return false;
423
- }
424
-
425
- async function ensureWriteAccess(context: any, permissionView?: string, mode?: string) {
426
- const idUser = context?.id_user;
427
- if (!idUser) {
428
- throw new Error('Mongo Explorer: Unauthorized');
429
- }
430
-
431
- const user = await Users.findOne({_id: idUser});
432
- if (!user) {
433
- throw new Error('Mongo Explorer: Unauthorized');
434
- }
435
-
436
- if (user.readonly) {
437
- throw new Error('Mongo Explorer: Readonly user');
438
- }
439
-
440
- const normalizedMode = normalizeExplorerMode(mode);
441
- if (normalizedMode === 'resolveio') {
442
- throw new Error('Mongo Explorer: ResolveIO mode is read only');
443
- }
444
-
445
- const allowedUsers = parseMongoExplorerWriteUsers();
446
- if (allowedUsers.length) {
447
- const username = String(user.username || '').trim().toLowerCase();
448
- const email = String(user.email || '').trim().toLowerCase();
449
- const id = String(user._id || '').trim();
450
- const isAllowed = allowedUsers.some(entry => {
451
- const normalized = String(entry || '').trim().toLowerCase();
452
- if (!normalized) {
453
- return false;
454
- }
455
- return normalized === username || (email && normalized === email) || (id && entry === id);
456
- });
457
-
458
- if (!isAllowed) {
459
- throw new Error('Mongo Explorer: Write access denied');
460
- }
461
- }
462
-
463
- if (user.roles?.super_admin) {
464
- return;
465
- }
466
-
467
- const normalizedPermission = typeof permissionView === 'string' ? permissionView.trim() : '';
468
-
469
- if (!normalizedPermission) {
470
- return;
471
- }
472
-
473
- if (userHasView(user, normalizedPermission)) {
474
- return;
475
- }
476
-
477
- throw new Error('Mongo Explorer: Write access denied');
478
- }
479
-
480
- function buildDeleteSafetyCollections(collectionRef: any): string[] {
481
- const schema = getSchemaDefinition(collectionRef);
482
- return Object.keys(schema).filter(path => isProtectedFieldPath(path) && path !== '_id');
483
- }
484
-
485
- async function buildDeleteImpact(database: string, sourceCollection: string, docId: string): Promise<MongoExplorerDeleteImpact> {
486
- const mainDb = ResolveIOServer.getServerConfig()?.DATABASE || '';
487
- if (database !== mainDb) {
488
- return {
489
- has_references: false,
490
- unresolved: true,
491
- collections: []
492
- };
493
- }
494
-
495
- const mongoManager = ResolveIOServer.getMongoManager();
496
- const collections = mongoManager?.collections ? mongoManager.collections() : [];
497
- const impacts: MongoExplorerDeleteImpactCollection[] = [];
498
- let unresolved = false;
499
-
500
- for (const collectionRef of collections) {
501
- const collectionName = collectionRef?.collectionName;
502
- if (!collectionName) {
503
- continue;
504
- }
505
- if (collectionName === `${sourceCollection}.versions`) {
506
- continue;
507
- }
508
-
509
- const referencePaths = buildDeleteSafetyCollections(collectionRef);
510
- if (!referencePaths.length) {
511
- continue;
512
- }
513
-
514
- const query = {
515
- $or: referencePaths.map(path => ({ [path]: docId }))
516
- };
517
-
518
- try {
519
- const docs = await collectionRef.find(query, { projection: { _id: 1 }, limit: 3 });
520
- if (Array.isArray(docs) && docs.length) {
521
- impacts.push({
522
- collection: collectionName,
523
- references: docs.length,
524
- sample_ids: docs.map(doc => String(doc?._id || '')).filter(Boolean)
525
- });
526
- }
527
- }
528
- catch {
529
- unresolved = true;
530
- }
531
- }
532
-
533
- return {
534
- has_references: impacts.length > 0,
535
- unresolved,
536
- collections: impacts.sort((a, b) => a.collection.localeCompare(b.collection))
537
- };
538
- }
539
-
540
- function normalizeOptionalString(value: any): string | undefined {
541
- if (typeof value === 'string') {
542
- const trimmed = value.trim();
543
- return trimmed.length ? trimmed : undefined;
544
- }
545
- if (value === null || value === undefined) {
546
- return undefined;
547
- }
548
- const normalized = String(value).trim();
549
- return normalized.length ? normalized : undefined;
550
- }
551
-
552
- function normalizePositiveNumber(value: any, fallback: number): number {
553
- const parsed = Number(value);
554
- if (!Number.isFinite(parsed) || parsed <= 0) {
555
- return fallback;
556
- }
557
- return parsed;
558
- }
559
-
560
- function parseBooleanValue(value: any, fallback: boolean): boolean {
561
- if (typeof value === 'boolean') {
562
- return value;
563
- }
564
- const normalized = String(value || '').trim().toLowerCase();
565
- if (!normalized.length) {
566
- return fallback;
567
- }
568
- if (['1', 'true', 'yes', 'on'].includes(normalized)) {
569
- return true;
570
- }
571
- if (['0', 'false', 'no', 'off'].includes(normalized)) {
572
- return false;
573
- }
574
- return fallback;
575
- }
576
-
577
- function truncateForRiskReview(value: string, maxLength = MAX_REVIEW_STRING_LENGTH): string {
578
- const normalized = String(value || '');
579
- if (normalized.length <= maxLength) {
580
- return normalized;
581
- }
582
- const diff = normalized.length - maxLength;
583
- return `${normalized.slice(0, maxLength)}...[+${diff} chars]`;
584
- }
585
-
586
- function sanitizeForRiskReview(value: any, depth = 0): any {
587
- if (value === null || value === undefined) {
588
- return value;
589
- }
590
-
591
- if (depth > MAX_REVIEW_DEPTH) {
592
- return '[Truncated depth]';
593
- }
594
-
595
- if (value instanceof Date) {
596
- return value.toISOString();
597
- }
598
-
599
- if (typeof value === 'string') {
600
- return truncateForRiskReview(value);
601
- }
602
-
603
- if (typeof value === 'number' || typeof value === 'boolean') {
604
- return value;
605
- }
606
-
607
- if (Array.isArray(value)) {
608
- const sanitized = value
609
- .slice(0, MAX_REVIEW_ARRAY_ITEMS)
610
- .map(item => sanitizeForRiskReview(item, depth + 1));
611
- if (value.length > MAX_REVIEW_ARRAY_ITEMS) {
612
- sanitized.push(`[${value.length - MAX_REVIEW_ARRAY_ITEMS} more item(s)]`);
613
- }
614
- return sanitized;
615
- }
616
-
617
- if (typeof value === 'object') {
618
- const output: Record<string, any> = {};
619
- const keys = Object.keys(value);
620
- const limitedKeys = keys.slice(0, MAX_REVIEW_OBJECT_KEYS);
621
- limitedKeys.forEach((key) => {
622
- if (SENSITIVE_REVIEW_FIELD_REGEX.test(key)) {
623
- output[key] = '[REDACTED]';
624
- return;
625
- }
626
- output[key] = sanitizeForRiskReview(value[key], depth + 1);
627
- });
628
- if (keys.length > MAX_REVIEW_OBJECT_KEYS) {
629
- output.__truncated_keys = keys.length - MAX_REVIEW_OBJECT_KEYS;
630
- }
631
- return output;
632
- }
633
-
634
- return truncateForRiskReview(String(value));
635
- }
636
-
637
- function pickChangedFields(beforeDocument: any, afterDocument: any): string[] {
638
- if (!beforeDocument || typeof beforeDocument !== 'object' || !afterDocument || typeof afterDocument !== 'object') {
639
- return [];
640
- }
641
-
642
- const changed: string[] = [];
643
- const fieldNames = new Set<string>([
644
- ...Object.keys(beforeDocument),
645
- ...Object.keys(afterDocument)
646
- ]);
647
-
648
- for (const field of fieldNames) {
649
- if (changed.length >= MAX_REVIEW_CHANGED_FIELDS) {
650
- break;
651
- }
652
- const beforeValue = safeStringify(beforeDocument[field]);
653
- const afterValue = safeStringify(afterDocument[field]);
654
- if (beforeValue !== afterValue) {
655
- changed.push(field);
656
- }
657
- }
658
-
659
- return changed;
660
- }
661
-
662
- function normalizeRiskLevel(value: any): MongoExplorerRiskLevel {
663
- const normalized = String(value || '').trim().toLowerCase();
664
- if (normalized === 'low') {
665
- return 'low';
666
- }
667
- if (normalized === 'medium') {
668
- return 'medium';
669
- }
670
- if (normalized === 'high') {
671
- return 'high';
672
- }
673
- if (normalized === 'critical') {
674
- return 'critical';
675
- }
676
- return 'high';
677
- }
678
-
679
- function normalizeRiskList(value: any): string[] {
680
- if (!Array.isArray(value)) {
681
- return [];
682
- }
683
- return value
684
- .map(item => normalizeOptionalString(item))
685
- .filter((item): item is string => !!item)
686
- .slice(0, MAX_REVIEW_LIST_ITEMS)
687
- .map(item => truncateForRiskReview(item, 220));
688
- }
689
-
690
- function buildFallbackRiskReview(operation: MongoExplorerRiskOperation, summary: string, model = ''): MongoExplorerRiskReview {
691
- return {
692
- operation,
693
- risk_level: 'high',
694
- should_block: true,
695
- summary: truncateForRiskReview(summary, 220),
696
- reasons: [
697
- 'AI review could not produce a reliable result.',
698
- 'Proceed only with explicit approval and manual dependency checks.'
699
- ],
700
- suggested_checks: [
701
- 'Confirm related records and id_* references before writing.',
702
- 'Validate that schema-required fields and date values remain valid.'
703
- ],
704
- confidence: 0,
705
- model: model || '',
706
- request_id: '',
707
- review_status: 'fallback',
708
- reviewed_at: new Date().toISOString()
709
- };
710
- }
711
-
712
- function buildDisabledRiskReview(operation: MongoExplorerRiskOperation): MongoExplorerRiskReview {
713
- return {
714
- operation,
715
- risk_level: 'low',
716
- should_block: false,
717
- summary: 'AI risk review is disabled by configuration.',
718
- reasons: [],
719
- suggested_checks: [],
720
- confidence: 1,
721
- model: '',
722
- request_id: '',
723
- review_status: 'disabled',
724
- reviewed_at: new Date().toISOString()
725
- };
726
- }
727
-
728
- function parseRiskReviewPayload(content: string): any {
729
- const normalized = String(content || '').trim();
730
- if (!normalized.length) {
731
- return {};
732
- }
733
-
734
- try {
735
- return JSON.parse(normalized);
736
- }
737
- catch {
738
- // Fall through and try to parse a JSON object embedded in plain text.
739
- }
740
-
741
- const start = normalized.indexOf('{');
742
- const end = normalized.lastIndexOf('}');
743
- if (start !== -1 && end > start) {
744
- const candidate = normalized.slice(start, end + 1);
745
- try {
746
- return JSON.parse(candidate);
747
- }
748
- catch {
749
- return {};
750
- }
751
- }
752
-
753
- return {};
754
- }
755
-
756
- function normalizeRiskReview(
757
- operation: MongoExplorerRiskOperation,
758
- payload: any,
759
- model: string,
760
- requestId: string
761
- ): MongoExplorerRiskReview {
762
- const riskLevel = normalizeRiskLevel(payload?.risk_level);
763
- const normalizedConfidence = Number(payload?.confidence);
764
- const confidence = Number.isFinite(normalizedConfidence)
765
- ? Math.max(0, Math.min(1, normalizedConfidence))
766
- : 0.6;
767
- const summary = normalizeOptionalString(payload?.summary)
768
- || `AI review marked this operation as ${riskLevel} risk.`;
769
- const reasons = normalizeRiskList(payload?.reasons);
770
- const suggestedChecks = normalizeRiskList(payload?.suggested_checks);
771
- const shouldBlock = payload?.should_block === true || riskLevel === 'critical';
772
-
773
- return {
774
- operation,
775
- risk_level: riskLevel,
776
- should_block: !!shouldBlock,
777
- summary: truncateForRiskReview(summary, 220),
778
- reasons,
779
- suggested_checks: suggestedChecks,
780
- confidence,
781
- model: model || '',
782
- request_id: requestId || '',
783
- review_status: 'ok',
784
- reviewed_at: new Date().toISOString()
785
- };
786
- }
787
-
788
- function resolveRiskReviewSettings() {
789
- const serverConfig = ResolveIOServer.getServerConfig() || {};
790
-
791
- const enabled = parseBooleanValue(
792
- serverConfig['MONGO_EXPLORER_ENABLE_AI_RISK_REVIEW'] ?? process.env.MONGO_EXPLORER_ENABLE_AI_RISK_REVIEW,
793
- true
794
- );
795
-
796
- const model = normalizeOptionalString(
797
- serverConfig['MONGO_EXPLORER_RISK_REVIEW_MODEL']
798
- || process.env.MONGO_EXPLORER_RISK_REVIEW_MODEL
799
- || serverConfig['AI_ASSISTANT_CODEX_MODEL']
800
- || process.env.AI_ASSISTANT_CODEX_MODEL
801
- || serverConfig['AI_DASHBOARD_CODEX_MODEL']
802
- || process.env.AI_DASHBOARD_CODEX_MODEL
803
- ) || DEFAULT_RISK_REVIEW_MODEL;
804
-
805
- const fallbackModel = normalizeOptionalString(
806
- serverConfig['MONGO_EXPLORER_RISK_REVIEW_FALLBACK_MODEL']
807
- || process.env.MONGO_EXPLORER_RISK_REVIEW_FALLBACK_MODEL
808
- || serverConfig['AI_ASSISTANT_CODEX_FALLBACK_MODEL']
809
- || process.env.AI_ASSISTANT_CODEX_FALLBACK_MODEL
810
- || serverConfig['AI_DASHBOARD_CODEX_FALLBACK_MODEL']
811
- || process.env.AI_DASHBOARD_CODEX_FALLBACK_MODEL
812
- );
813
-
814
- const timeoutMs = normalizePositiveNumber(
815
- serverConfig['MONGO_EXPLORER_RISK_REVIEW_TIMEOUT_MS'] ?? process.env.MONGO_EXPLORER_RISK_REVIEW_TIMEOUT_MS,
816
- DEFAULT_RISK_REVIEW_TIMEOUT_MS
817
- );
818
-
819
- const maxTokens = normalizePositiveNumber(
820
- serverConfig['MONGO_EXPLORER_RISK_REVIEW_MAX_TOKENS'] ?? process.env.MONGO_EXPLORER_RISK_REVIEW_MAX_TOKENS,
821
- DEFAULT_RISK_REVIEW_MAX_TOKENS
822
- );
823
-
824
- const maxRetries = normalizePositiveNumber(
825
- serverConfig['OPENAI_MAX_RETRIES'] ?? process.env.OPENAI_MAX_RETRIES,
826
- 1
827
- );
828
-
829
- const retryDelayMs = normalizePositiveNumber(
830
- serverConfig['OPENAI_RETRY_DELAY_MS'] ?? process.env.OPENAI_RETRY_DELAY_MS,
831
- 750
832
- );
833
-
834
- const apiKey = normalizeOptionalString(serverConfig['OPENAI_API_KEY'] || process.env.OPENAI_API_KEY) || '';
835
- const baseUrl = normalizeOptionalString(serverConfig['OPENAI_BASE_URL'] || process.env.OPENAI_BASE_URL);
836
-
837
- return {
838
- enabled,
839
- apiKey,
840
- baseUrl,
841
- model,
842
- fallbackModel,
843
- timeoutMs,
844
- maxTokens,
845
- maxRetries,
846
- retryDelayMs
847
- };
848
- }
849
-
850
- function buildCodexPrompt(systemPrompt: string, userPrompt: string): string {
851
- return `System:\n${systemPrompt}\n\nUser:\n${userPrompt}`.trim();
852
- }
853
-
854
- function buildCodexClient(settings: {
855
- apiKey: string;
856
- baseUrl?: string;
857
- model: string;
858
- fallbackModel?: string;
859
- maxRetries?: number;
860
- retryDelayMs?: number;
861
- }): CodexClient {
862
- const fallbackModels: string[] = [];
863
- const fallback = normalizeOptionalString(settings.fallbackModel);
864
- if (fallback && fallback !== settings.model) {
865
- fallbackModels.push(fallback);
866
- }
867
- return new CodexClient({
868
- apiKey: settings.apiKey,
869
- baseUrl: settings.baseUrl,
870
- model: settings.model,
871
- ...(fallbackModels.length ? { fallbackModel: fallbackModels[0], fallbackModels } : {}),
872
- maxRetries: round(settings.maxRetries || 0),
873
- retryDelayMs: round(settings.retryDelayMs || 0)
874
- });
875
- }
876
-
877
- function estimateCodexUsage(messages: Array<{ role: string; content: string }>, responseText: string, model: string) {
878
- const inputTokens = countChatTokens(messages, model);
879
- const outputTokens = countTokens(responseText || '', model);
880
- return {
881
- inputTokens,
882
- outputTokens,
883
- totalTokens: inputTokens + outputTokens
884
- };
885
- }
886
-
887
- function buildRiskReviewPrompt(input: MongoExplorerRiskReviewInput): string {
888
- const payload = {
889
- database: input.database,
890
- collection: input.collection,
891
- operation: input.operation,
892
- mode: input.mode,
893
- changed_fields: pickChangedFields(input.before_document, input.after_document),
894
- delete_impact: sanitizeForRiskReview(input.delete_impact || null),
895
- before_document: sanitizeForRiskReview(input.before_document || null),
896
- after_document: sanitizeForRiskReview(input.after_document || null)
897
- };
898
-
899
- return [
900
- 'Review this MongoDB write operation for runtime and data integrity risk.',
901
- 'Focus on foreign-key style id_* dependencies, schema compatibility, destructive impact, and financial/operational record safety.',
902
- 'Return JSON only.',
903
- JSON.stringify(payload, null, 2)
904
- ].join('\n');
905
- }
906
-
907
- async function reviewOperationRisk(input: MongoExplorerRiskReviewInput): Promise<MongoExplorerRiskReview> {
908
- const settings = resolveRiskReviewSettings();
909
- if (!settings.enabled) {
910
- return buildDisabledRiskReview(input.operation);
911
- }
912
-
913
- if (!settings.apiKey) {
914
- return buildFallbackRiskReview(input.operation, 'AI risk review unavailable: AI API key is missing.');
915
- }
916
-
917
- const client = buildCodexClient(settings);
918
-
919
- const systemPrompt = [
920
- 'You are a MongoDB operation safety reviewer for a production SaaS application.',
921
- 'Respond with a single JSON object only.',
922
- 'Required keys:',
923
- 'risk_level ("low" | "medium" | "high" | "critical"),',
924
- 'should_block (boolean),',
925
- 'summary (string),',
926
- 'reasons (string[]),',
927
- 'suggested_checks (string[]),',
928
- 'confidence (number between 0 and 1).',
929
- 'Keep summary concise (<= 220 chars).'
930
- ].join(' ');
931
- const userPrompt = buildRiskReviewPrompt(input);
932
- const prompt = buildCodexPrompt(systemPrompt, userPrompt);
933
-
934
- try {
935
- const responseText = await client.run(prompt, {
936
- timeoutMs: round(settings.timeoutMs),
937
- threadOptions: {
938
- model: settings.model,
939
- sandboxMode: 'read-only',
940
- skipGitRepoCheck: true,
941
- networkAccessEnabled: false,
942
- webSearchMode: 'disabled',
943
- webSearchEnabled: false,
944
- approvalPolicy: 'never'
945
- }
946
- });
947
-
948
- const payload = parseRiskReviewPayload(responseText);
949
- return normalizeRiskReview(input.operation, payload, settings.model, '');
950
- }
951
- catch (err) {
952
- const detail = err?.message ? String(err.message) : 'Unknown AI review error';
953
- return buildFallbackRiskReview(input.operation, `AI risk review failed: ${truncateForRiskReview(detail, 160)}`, settings.model);
954
- }
955
- }
956
-
957
- function normalizeAiAction(value: any): MongoExplorerAiAction {
958
- const normalized = normalizeOptionalString(value) || '';
959
- return normalized.toLowerCase() === 'aggregate' ? 'aggregate' : 'find';
960
- }
961
-
962
- function sanitizeAiCollections(raw: any[]): string[] {
963
- const values: string[] = [];
964
- const seen = new Set<string>();
965
- (raw || []).forEach((entry) => {
966
- const normalized = normalizeOptionalString((entry as any)?.collection || (entry as any)?.name || entry);
967
- if (!normalized) {
968
- return;
969
- }
970
- const key = normalized.toLowerCase();
971
- if (seen.has(key)) {
972
- return;
973
- }
974
- seen.add(key);
975
- values.push(normalized);
976
- });
977
- return values.slice(0, MAX_AI_SUGGEST_COLLECTIONS);
978
- }
979
-
980
- function sanitizeAiFields(raw: any[], fallbackCollection: string): MongoExplorerAiField[] {
981
- const fields: MongoExplorerAiField[] = [];
982
- const seen = new Set<string>();
983
- (raw || []).forEach((entry) => {
984
- const path = normalizeOptionalString(entry?.path || entry?.field_path || entry?.fieldPath);
985
- if (!path) {
986
- return;
987
- }
988
- const collection = normalizeOptionalString(
989
- entry?.collection || entry?.collection_name || entry?.collectionName
990
- ) || fallbackCollection || '';
991
- const key = `${collection.toLowerCase()}::${path.toLowerCase()}`;
992
- if (seen.has(key)) {
993
- return;
994
- }
995
- seen.add(key);
996
- fields.push({
997
- path,
998
- label: normalizeOptionalString(entry?.label || entry?.field_path_name || entry?.fieldPathName) || path,
999
- type: normalizeOptionalString(entry?.type || entry?.field_type || entry?.fieldType) || 'Any',
1000
- collection
1001
- });
1002
- });
1003
- return fields.slice(0, MAX_AI_SUGGEST_FIELDS);
1004
- }
1005
-
1006
- function deriveAiFieldsFromCollection(database: string, collection: string): MongoExplorerAiField[] {
1007
- if (!collection) {
1008
- return [];
1009
- }
1010
- const { managerCollection } = resolveCollectionHandle(database, collection);
1011
- if (!managerCollection) {
1012
- return [];
1013
- }
1014
- const schema = getSchemaDefinition(managerCollection);
1015
- return Object.keys(schema)
1016
- .sort((a, b) => a.localeCompare(b))
1017
- .slice(0, MAX_AI_SUGGEST_FIELDS)
1018
- .map((path) => {
1019
- const definition = schema[path];
1020
- return {
1021
- path,
1022
- label: toLabel(path),
1023
- type: getSchemaTypeName(definition),
1024
- collection
1025
- };
1026
- });
1027
- }
1028
-
1029
- function resolveCollectionFromList(value: any, collections: string[], fallback = ''): string {
1030
- const normalized = normalizeOptionalString(value);
1031
- if (normalized) {
1032
- const matched = (collections || []).find(entry => entry.toLowerCase() === normalized.toLowerCase());
1033
- if (matched) {
1034
- return matched;
1035
- }
1036
- }
1037
- if (fallback) {
1038
- return fallback;
1039
- }
1040
- return collections?.[0] || '';
1041
- }
1042
-
1043
- function normalizeAiResultLimit(value: any, fallback = 100): number {
1044
- const fallbackValue = Math.min(Math.max(fallback, 1), MAX_AI_SUGGEST_RESULTS);
1045
- const parsed = Number(value);
1046
- if (!Number.isFinite(parsed) || parsed <= 0) {
1047
- return fallbackValue;
1048
- }
1049
- return Math.min(Math.max(round(parsed), 1), MAX_AI_SUGGEST_RESULTS);
1050
- }
1051
-
1052
- function normalizeAiSkip(value: any): number {
1053
- const parsed = Number(value);
1054
- if (!Number.isFinite(parsed) || parsed < 0) {
1055
- return 0;
1056
- }
1057
- return Math.max(0, round(parsed));
1058
- }
1059
-
1060
- function normalizeAiObject(value: any): Record<string, any> {
1061
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
1062
- return {};
1063
- }
1064
- return value;
1065
- }
1066
-
1067
- function hasObjectKeys(value: any): boolean {
1068
- return !!value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
1069
- }
1070
-
1071
- function parseAiPlanPayload(content: string): any {
1072
- const normalized = String(content || '').trim();
1073
- if (!normalized.length) {
1074
- return {};
1075
- }
1076
-
1077
- try {
1078
- return JSON.parse(normalized);
1079
- }
1080
- catch {
1081
- // Fall through and parse embedded JSON object.
1082
- }
1083
-
1084
- const start = normalized.indexOf('{');
1085
- const end = normalized.lastIndexOf('}');
1086
- if (start !== -1 && end > start) {
1087
- try {
1088
- return JSON.parse(normalized.slice(start, end + 1));
1089
- }
1090
- catch {
1091
- return {};
1092
- }
1093
- }
1094
-
1095
- return {};
1096
- }
1097
-
1098
- function resolveMongoExplorerAiSettings() {
1099
- const serverConfig = ResolveIOServer.getServerConfig() || {};
1100
- const apiKey = normalizeOptionalString(serverConfig['OPENAI_API_KEY'] || process.env.OPENAI_API_KEY) || '';
1101
- const baseUrl = normalizeOptionalString(serverConfig['OPENAI_BASE_URL'] || process.env.OPENAI_BASE_URL);
1102
-
1103
- const model = normalizeOptionalString(
1104
- serverConfig['MONGO_EXPLORER_AI_MODEL']
1105
- || process.env.MONGO_EXPLORER_AI_MODEL
1106
- || serverConfig['AI_ASSISTANT_CODEX_MODEL']
1107
- || process.env.AI_ASSISTANT_CODEX_MODEL
1108
- ) || DEFAULT_AI_SUGGEST_MODEL;
1109
-
1110
- const fallbackModel = normalizeOptionalString(
1111
- serverConfig['MONGO_EXPLORER_AI_FALLBACK_MODEL']
1112
- || process.env.MONGO_EXPLORER_AI_FALLBACK_MODEL
1113
- || serverConfig['AI_ASSISTANT_CODEX_FALLBACK_MODEL']
1114
- || process.env.AI_ASSISTANT_CODEX_FALLBACK_MODEL
1115
- ) || DEFAULT_AI_SUGGEST_FALLBACK_MODEL;
1116
-
1117
- const timeoutMs = normalizePositiveNumber(
1118
- serverConfig['MONGO_EXPLORER_AI_TIMEOUT_MS'] ?? process.env.MONGO_EXPLORER_AI_TIMEOUT_MS,
1119
- DEFAULT_AI_SUGGEST_TIMEOUT_MS
1120
- );
1121
-
1122
- const maxTokens = normalizePositiveNumber(
1123
- serverConfig['MONGO_EXPLORER_AI_MAX_TOKENS'] ?? process.env.MONGO_EXPLORER_AI_MAX_TOKENS,
1124
- DEFAULT_AI_SUGGEST_MAX_TOKENS
1125
- );
1126
-
1127
- const maxRetries = normalizePositiveNumber(
1128
- serverConfig['OPENAI_MAX_RETRIES'] ?? process.env.OPENAI_MAX_RETRIES,
1129
- 1
1130
- );
1131
-
1132
- const retryDelayMs = normalizePositiveNumber(
1133
- serverConfig['OPENAI_RETRY_DELAY_MS'] ?? process.env.OPENAI_RETRY_DELAY_MS,
1134
- 750
1135
- );
1136
-
1137
- return {
1138
- apiKey,
1139
- baseUrl,
1140
- model,
1141
- fallbackModel,
1142
- timeoutMs,
1143
- maxTokens,
1144
- maxRetries,
1145
- retryDelayMs
1146
- };
1147
- }
1148
-
1149
- function buildMongoExplorerAiSystemPrompt(): string {
1150
- return [
1151
- 'You are a MongoDB query planner for a read-only Mongo Explorer UI.',
1152
- 'Return a single JSON object and nothing else.',
1153
- 'Supported schema:',
1154
- '{',
1155
- ' "action": "find|aggregate",',
1156
- ' "collection": "string",',
1157
- ' "query": { ... },',
1158
- ' "pipeline": [{ ... }],',
1159
- ' "options": {',
1160
- ' "projection": { "field": 1 },',
1161
- ' "sort": { "field": -1 },',
1162
- ' "limit": 100,',
1163
- ' "skip": 0,',
1164
- ' "includeTotal": true,',
1165
- ' "allowDiskUse": true',
1166
- ' },',
1167
- ' "notes": "short summary"',
1168
- '}',
1169
- 'Rules:',
1170
- '- Use only provided collection names and field paths.',
1171
- '- Read-only only. Never output write operations, update/delete commands, or aggregation stages $out/$merge.',
1172
- '- Prefer action=find for direct lookups and simple filters.',
1173
- '- Use action=aggregate for grouped totals, rankings, or trend buckets.',
1174
- '- Keep options.limit between 1 and 500.',
1175
- '- If request is ambiguous, use selected_collection and a conservative limit.'
1176
- ].join('\n');
1177
- }
1178
-
1179
- function buildMongoExplorerAiUserPrompt(input: {
1180
- prompt: string;
1181
- selectedCollection: string;
1182
- availableCollections: string[];
1183
- availableFields: MongoExplorerAiField[];
1184
- maxResults: number;
1185
- }): string {
1186
- const payload = {
1187
- request: input.prompt,
1188
- selected_collection: input.selectedCollection || '',
1189
- max_results: input.maxResults,
1190
- available_collections: input.availableCollections || [],
1191
- available_fields: input.availableFields || []
1192
- };
1193
- return JSON.stringify(payload);
1194
- }
1195
-
1196
- function sanitizeAggregatePipeline(rawPipeline: any, limit: number): { pipeline: any[]; removedRestricted: boolean } {
1197
- const source = Array.isArray(rawPipeline) ? rawPipeline : [];
1198
- const sanitized: any[] = [];
1199
- let removedRestricted = false;
1200
-
1201
- source.forEach((stage) => {
1202
- if (!stage || typeof stage !== 'object' || Array.isArray(stage)) {
1203
- return;
1204
- }
1205
-
1206
- const keys = Object.keys(stage);
1207
- if (!keys.length) {
1208
- return;
1209
- }
1210
-
1211
- const stageName = keys[0];
1212
- if (RESTRICTED_AGGREGATE_STAGES.has(String(stageName).toLowerCase())) {
1213
- removedRestricted = true;
1214
- return;
1215
- }
1216
-
1217
- if (stageName === '$limit') {
1218
- sanitized.push({ $limit: normalizeAiResultLimit((stage as any).$limit, limit) });
1219
- return;
1220
- }
1221
-
1222
- sanitized.push(stage);
1223
- });
1224
-
1225
- if (!sanitized.some(stage => Object.keys(stage || {})[0] === '$limit')) {
1226
- sanitized.push({ $limit: limit });
1227
- }
1228
-
1229
- return {
1230
- pipeline: sanitized,
1231
- removedRestricted
1232
- };
1233
- }
1234
-
1235
- function sanitizeFindOptions(raw: any, fallbackLimit: number): {
1236
- projection?: Record<string, any>;
1237
- sort?: Record<string, any>;
1238
- limit: number;
1239
- skip: number;
1240
- includeTotal: boolean;
1241
- } {
1242
- const options = normalizeAiObject(raw);
1243
- return {
1244
- projection: hasObjectKeys(options.projection) ? options.projection : undefined,
1245
- sort: hasObjectKeys(options.sort) ? options.sort : undefined,
1246
- limit: normalizeAiResultLimit(options.limit, fallbackLimit),
1247
- skip: normalizeAiSkip(options.skip),
1248
- includeTotal: options.includeTotal === true
1249
- };
1250
- }
1251
-
1252
- function buildMongoExplorerAiNotes(
1253
- rawNotes: any,
1254
- action: MongoExplorerAiAction,
1255
- collection: string,
1256
- rowCount: number,
1257
- total: number | null,
1258
- removedRestricted: boolean
1259
- ): string {
1260
- const notes: string[] = [];
1261
- const base = normalizeOptionalString(rawNotes);
1262
- if (base) {
1263
- notes.push(base);
1264
- }
1265
-
1266
- const actionLabel = action === 'aggregate' ? 'aggregate pipeline' : 'query';
1267
- if (typeof total === 'number' && total >= 0) {
1268
- notes.push(`Applied ${actionLabel} on ${collection}. Loaded ${rowCount} of ${total} rows.`);
1269
- }
1270
- else {
1271
- notes.push(`Applied ${actionLabel} on ${collection}. Loaded ${rowCount} rows.`);
1272
- }
1273
-
1274
- if (removedRestricted) {
1275
- notes.push('Removed restricted write stages from the generated pipeline.');
1276
- }
1277
-
1278
- return notes.join(' ').trim();
1279
- }
1280
-
1281
- async function resolveUsageClientId(idClientInput?: string, idUser?: string): Promise<string> {
1282
- const normalized = normalizeOptionalString(idClientInput);
1283
- if (normalized) {
1284
- return normalized;
1285
- }
1286
- if (!idUser) {
1287
- return '';
1288
- }
1289
- try {
1290
- const user = await Users.findById(idUser);
1291
- return normalizeOptionalString(user?.other?.id_client || user?.other?.idClient) || '';
1292
- }
1293
- catch {
1294
- return '';
1295
- }
1296
- }
1297
-
1298
- async function executeMongoExplorerAi(payload: MongoExplorerAiPayload, context: any) {
1299
- const input = payload || {};
1300
- const prompt = normalizeOptionalString(input.prompt);
1301
- if (!prompt) {
1302
- throw new Error('Prompt is required.');
1303
- }
1304
-
1305
- const database = resolveDatabaseName(input.database);
1306
- const db = resolveDatabase(database);
1307
-
1308
- let availableCollections = sanitizeAiCollections(input.available_collections || []);
1309
- if (!availableCollections.length) {
1310
- const listed = await db.listCollections().toArray();
1311
- availableCollections = listed
1312
- .map(collection => normalizeOptionalString(collection?.name))
1313
- .filter((collection): collection is string => !!collection)
1314
- .slice(0, MAX_AI_SUGGEST_COLLECTIONS);
1315
- }
1316
-
1317
- if (!availableCollections.length) {
1318
- throw new Error('Mongo Explorer AI assistant: no collections available.');
1319
- }
1320
-
1321
- const selectedCollection = resolveCollectionFromList(
1322
- input.selected_collection,
1323
- availableCollections,
1324
- availableCollections[0]
1325
- );
1326
-
1327
- let availableFields = sanitizeAiFields(input.available_fields || [], selectedCollection);
1328
- if (!availableFields.length && selectedCollection) {
1329
- availableFields = deriveAiFieldsFromCollection(database, selectedCollection);
1330
- }
1331
-
1332
- const settings = resolveMongoExplorerAiSettings();
1333
- if (!settings.apiKey) {
1334
- throw new Error('AI API key missing. Add an AI API key to server config.');
1335
- }
1336
-
1337
- const maxResults = normalizeAiResultLimit(input.max_results, 100);
1338
- const client = buildCodexClient(settings);
1339
- const messages: Array<{ role: 'system' | 'user'; content: string }> = [
1340
- { role: 'system', content: buildMongoExplorerAiSystemPrompt() },
1341
- {
1342
- role: 'user',
1343
- content: buildMongoExplorerAiUserPrompt({
1344
- prompt,
1345
- selectedCollection,
1346
- availableCollections,
1347
- availableFields,
1348
- maxResults
1349
- })
1350
- }
1351
- ];
1352
- const responseText = await client.run(
1353
- buildCodexPrompt(messages[0].content, messages[1].content),
1354
- {
1355
- timeoutMs: round(settings.timeoutMs),
1356
- threadOptions: {
1357
- model: settings.model,
1358
- sandboxMode: 'read-only',
1359
- skipGitRepoCheck: true,
1360
- networkAccessEnabled: false,
1361
- webSearchMode: 'disabled',
1362
- webSearchEnabled: false,
1363
- approvalPolicy: 'never'
1364
- }
1365
- }
1366
- );
1367
-
1368
- const parsed = parseAiPlanPayload(responseText);
1369
- const action = normalizeAiAction(parsed?.action || (Array.isArray(parsed?.pipeline) ? 'aggregate' : 'find'));
1370
- const collection = resolveCollectionFromList(
1371
- parsed?.collection || parsed?.collection_name,
1372
- availableCollections,
1373
- selectedCollection || availableCollections[0]
1374
- );
1375
-
1376
- if (!collection) {
1377
- throw new Error('Mongo Explorer AI assistant could not resolve a collection.');
1378
- }
1379
-
1380
- let plan: MongoExplorerAiPlan = {
1381
- action,
1382
- collection,
1383
- options: {}
1384
- };
1385
- let removedRestrictedStages = false;
1386
-
1387
- if (action === 'aggregate') {
1388
- const optionsRaw = normalizeAiObject(parsed?.options);
1389
- const aggregateLimit = normalizeAiResultLimit(optionsRaw.limit ?? parsed?.limit, maxResults);
1390
- const pipelineResult = sanitizeAggregatePipeline(parsed?.pipeline, aggregateLimit);
1391
- removedRestrictedStages = pipelineResult.removedRestricted;
1392
-
1393
- const aggregateOptions = {
1394
- allowDiskUse: optionsRaw.allowDiskUse === true
1395
- };
1396
-
1397
- const aggregateRows = await db.collection(collection).aggregate(pipelineResult.pipeline, aggregateOptions).toArray();
1398
- const rows = (aggregateRows || []).slice(0, aggregateLimit);
1399
-
1400
- plan = {
1401
- action,
1402
- collection,
1403
- pipeline: pipelineResult.pipeline,
1404
- options: {
1405
- allowDiskUse: aggregateOptions.allowDiskUse,
1406
- limit: aggregateLimit
1407
- },
1408
- documents: rows,
1409
- total: null
1410
- };
1411
- }
1412
- else {
1413
- const query = normalizeAiObject(parsed?.query);
1414
- const options = sanitizeFindOptions(parsed?.options, maxResults);
1415
- const findOptions: any = {
1416
- limit: options.limit,
1417
- skip: options.skip
1418
- };
1419
- if (options.projection) {
1420
- findOptions.projection = options.projection;
1421
- }
1422
- if (options.sort) {
1423
- findOptions.sort = options.sort;
1424
- }
1425
-
1426
- const rows = await db.collection(collection).find(query, findOptions).toArray();
1427
- const total = options.includeTotal ? await db.collection(collection).countDocuments(query) : null;
1428
-
1429
- plan = {
1430
- action,
1431
- collection,
1432
- query,
1433
- options: {
1434
- ...(options.projection ? { projection: options.projection } : {}),
1435
- ...(options.sort ? { sort: options.sort } : {}),
1436
- limit: options.limit,
1437
- skip: options.skip,
1438
- includeTotal: options.includeTotal
1439
- },
1440
- documents: rows,
1441
- total
1442
- };
1443
- }
1444
-
1445
- plan.notes = buildMongoExplorerAiNotes(
1446
- parsed?.notes,
1447
- plan.action,
1448
- plan.collection,
1449
- Array.isArray(plan.documents) ? plan.documents.length : 0,
1450
- typeof plan.total === 'number' ? plan.total : null,
1451
- removedRestrictedStages
1452
- );
1453
-
1454
- const usage = estimateCodexUsage(messages, responseText, settings.model);
1455
- const idClient = await resolveUsageClientId(input.id_client, context?.id_user);
1456
- if (usage.totalTokens) {
1457
- await recordOpenAIUsage({
1458
- id_client: idClient || '',
1459
- model: settings.model || 'unknown',
1460
- input_tokens: usage.inputTokens || 0,
1461
- output_tokens: usage.outputTokens || 0,
1462
- total_tokens: usage.totalTokens || 0,
1463
- category: 'mongo-explorer-ai',
1464
- id_request: ''
1465
- });
1466
- }
1467
-
1468
- return {
1469
- notes: plan.notes,
1470
- plan,
1471
- model: settings.model,
1472
- usage: {
1473
- input_tokens: usage.inputTokens || 0,
1474
- output_tokens: usage.outputTokens || 0,
1475
- total_tokens: usage.totalTokens || 0
1476
- }
1477
- };
1478
- }
1479
-
1480
- export function loadMongoExplorerMethods(methodManager: MethodManager) {
1481
- methodManager.methods({
1482
- mongoExplorerAiSuggest: {
1483
- check: new SimpleSchema({
1484
- payload: {
1485
- type: Object,
1486
- blackbox: true
1487
- }
1488
- }),
1489
- function: async function(payload: any) {
1490
- return executeMongoExplorerAi(payload || {}, this);
1491
- }
1492
- },
1493
- mongoExplorerListCollections: {
1494
- check: new SimpleSchema({
1495
- database: {
1496
- type: String,
1497
- optional: true
1498
- }
1499
- }),
1500
- function: async function(database?: string) {
1501
- const db = resolveDatabase(database);
1502
- const collections = await db.listCollections().toArray();
1503
- return collections
1504
- .map(col => ({
1505
- name: col.name,
1506
- type: col.type || 'collection'
1507
- }))
1508
- .sort((a, b) => a.name.localeCompare(b.name));
1509
- }
1510
- },
1511
- mongoExplorerFind: {
1512
- bypassSession: true,
1513
- check: new SimpleSchema({
1514
- database: {
1515
- type: String,
1516
- optional: true
1517
- },
1518
- collection: {
1519
- type: String
1520
- },
1521
- query: {
1522
- type: Object,
1523
- blackbox: true,
1524
- optional: true
1525
- },
1526
- options: {
1527
- type: Object,
1528
- blackbox: true,
1529
- optional: true
1530
- }
1531
- }),
1532
- function: async function(database: string, collection: string, query: any = {}, options?) {
1533
- const db = resolveDatabase(database);
1534
- const normalized = normalizeFindOptions(options);
1535
- const documents = await db.collection(collection).find(query || {}, normalized.findOptions).toArray();
1536
- let total = null;
1537
-
1538
- if (normalized.includeTotal) {
1539
- total = await db.collection(collection).countDocuments(query || {});
1540
- }
1541
-
1542
- return {
1543
- documents,
1544
- total
1545
- };
1546
- }
1547
- },
1548
- mongoExplorerGetCollectionSchema: {
1549
- check: new SimpleSchema({
1550
- database: {
1551
- type: String,
1552
- optional: true
1553
- },
1554
- collection: {
1555
- type: String
1556
- }
1557
- }),
1558
- function: function(database: string, collection: string) {
1559
- const dbName = resolveDatabaseName(database);
1560
- const { managerCollection } = resolveCollectionHandle(dbName, collection);
1561
- if (!managerCollection) {
1562
- return Promise.resolve({
1563
- collection,
1564
- has_schema: false,
1565
- fields: []
1566
- });
1567
- }
1568
-
1569
- const schema = getSchemaDefinition(managerCollection);
1570
- const fields = Object.keys(schema)
1571
- .sort((a, b) => a.localeCompare(b))
1572
- .map((path) => {
1573
- const definition = schema[path];
1574
- return {
1575
- path,
1576
- label: toLabel(path),
1577
- type: getSchemaTypeName(definition),
1578
- optional: definition?.optional === true,
1579
- protected: isProtectedFieldPath(path),
1580
- depth: path.split('.').filter((segment: string) => segment !== '$').length - 1
1581
- };
1582
- });
1583
-
1584
- return Promise.resolve({
1585
- collection,
1586
- has_schema: true,
1587
- fields
1588
- });
1589
- }
1590
- },
1591
- mongoExplorerAggregate: {
1592
- bypassSession: true,
1593
- check: new SimpleSchema({
1594
- database: {
1595
- type: String,
1596
- optional: true
1597
- },
1598
- collection: {
1599
- type: String
1600
- },
1601
- pipeline: {
1602
- type: Array
1603
- },
1604
- 'pipeline.$': {
1605
- type: Object,
1606
- blackbox: true
1607
- },
1608
- options: {
1609
- type: Object,
1610
- optional: true,
1611
- blackbox: true
1612
- }
1613
- }),
1614
- function: async function(database: string, collection: string, pipeline: any[], options: any = {}) {
1615
- const db = resolveDatabase(database);
1616
- return db.collection(collection).aggregate(pipeline || [], options || undefined).toArray();
1617
- }
1618
- },
1619
- mongoExplorerCommand: {
1620
- check: new SimpleSchema({
1621
- database: {
1622
- type: String,
1623
- optional: true
1624
- },
1625
- command: {
1626
- type: Object,
1627
- blackbox: true
1628
- },
1629
- permissionView: {
1630
- type: String,
1631
- optional: true
1632
- },
1633
- mode: {
1634
- type: String,
1635
- optional: true
1636
- }
1637
- }),
1638
- function: async function(database: string, command: any, permissionView?: string, mode?: string) {
1639
- await ensureWriteAccess(this, permissionView, mode);
1640
- const db = resolveDatabase(database);
1641
- return db.command(command);
1642
- }
1643
- },
1644
- mongoExplorerInsertDocument: {
1645
- check: new SimpleSchema({
1646
- database: {
1647
- type: String,
1648
- optional: true
1649
- },
1650
- collection: {
1651
- type: String
1652
- },
1653
- document: {
1654
- type: Object,
1655
- blackbox: true
1656
- },
1657
- permissionView: {
1658
- type: String,
1659
- optional: true
1660
- },
1661
- mode: {
1662
- type: String,
1663
- optional: true
1664
- }
1665
- }),
1666
- function: async function(database: string, collection: string, document: any, permissionView?: string, mode?: string) {
1667
- await ensureWriteAccess(this, permissionView, mode);
1668
- const dbName = resolveDatabaseName(database);
1669
- const { managerCollection, dbCollection } = resolveCollectionHandle(dbName, collection);
1670
-
1671
- if (!document || typeof document !== 'object') {
1672
- throw new Error('Mongo Explorer: Document is required');
1673
- }
1674
-
1675
- if (!managerCollection && !allowUnschemaizedWrites()) {
1676
- throw new Error('Mongo Explorer: Writes require schema-backed collections. Set MONGO_EXPLORER_ALLOW_UNSCHEMATIZED_WRITE=true to bypass.');
1677
- }
1678
-
1679
- if (!document._id) {
1680
- document._id = objectIdHexString();
1681
- }
1682
-
1683
- if (document.__v === undefined) {
1684
- document.__v = 0;
1685
- }
1686
-
1687
- if (managerCollection) {
1688
- coerceDateFields(managerCollection, document);
1689
- await managerCollection.insertOne(document);
1690
- }
1691
- else {
1692
- await dbCollection.insertOne(document);
1693
- }
1694
-
1695
- return document._id;
1696
- }
1697
- },
1698
- mongoExplorerReplaceDocument: {
1699
- check: new SimpleSchema({
1700
- database: {
1701
- type: String,
1702
- optional: true
1703
- },
1704
- collection: {
1705
- type: String
1706
- },
1707
- document: {
1708
- type: Object,
1709
- blackbox: true
1710
- },
1711
- permissionView: {
1712
- type: String,
1713
- optional: true
1714
- },
1715
- mode: {
1716
- type: String,
1717
- optional: true
1718
- }
1719
- }),
1720
- function: async function(database: string, collection: string, document: any, permissionView?: string, mode?: string) {
1721
- await ensureWriteAccess(this, permissionView, mode);
1722
- const dbName = resolveDatabaseName(database);
1723
- const { managerCollection, dbCollection } = resolveCollectionHandle(dbName, collection);
1724
-
1725
- if (!document || typeof document !== 'object' || !document._id) {
1726
- throw new Error('Mongo Explorer: Document with _id is required');
1727
- }
1728
-
1729
- const currentDoc = managerCollection
1730
- ? await managerCollection.findOne({_id: document._id})
1731
- : await dbCollection.findOne({_id: document._id});
1732
- if (!currentDoc) {
1733
- throw new Error('Mongo Explorer: Document not found');
1734
- }
1735
-
1736
- ensureProtectedFieldsUnchanged(currentDoc, document);
1737
-
1738
- if (!managerCollection && !allowUnschemaizedWrites()) {
1739
- throw new Error('Mongo Explorer: Writes require schema-backed collections. Set MONGO_EXPLORER_ALLOW_UNSCHEMATIZED_WRITE=true to bypass.');
1740
- }
1741
-
1742
- if (managerCollection) {
1743
- coerceDateFields(managerCollection, document);
1744
- await managerCollection.replaceOne({_id: document._id}, document);
1745
- }
1746
- else {
1747
- await dbCollection.replaceOne({_id: document._id}, document);
1748
- }
1749
-
1750
- return true;
1751
- }
1752
- },
1753
- mongoExplorerReviewOperationRisk: {
1754
- check: new SimpleSchema({
1755
- database: {
1756
- type: String,
1757
- optional: true
1758
- },
1759
- collection: {
1760
- type: String
1761
- },
1762
- operation: {
1763
- type: String,
1764
- allowedValues: ['insert', 'replace', 'delete', 'command']
1765
- },
1766
- before_document: {
1767
- type: Object,
1768
- blackbox: true,
1769
- optional: true
1770
- },
1771
- after_document: {
1772
- type: Object,
1773
- blackbox: true,
1774
- optional: true
1775
- },
1776
- delete_impact: {
1777
- type: Object,
1778
- blackbox: true,
1779
- optional: true
1780
- },
1781
- permissionView: {
1782
- type: String,
1783
- optional: true
1784
- },
1785
- mode: {
1786
- type: String,
1787
- optional: true
1788
- }
1789
- }),
1790
- function: async function(
1791
- database: string,
1792
- collection: string,
1793
- operation: MongoExplorerRiskOperation,
1794
- before_document?: any,
1795
- after_document?: any,
1796
- delete_impact?: MongoExplorerDeleteImpact,
1797
- permissionView?: string,
1798
- mode?: string
1799
- ) {
1800
- await ensureWriteAccess(this, permissionView, mode);
1801
- const dbName = resolveDatabaseName(database);
1802
-
1803
- return reviewOperationRisk({
1804
- database: dbName,
1805
- collection,
1806
- operation,
1807
- mode: normalizeExplorerMode(mode),
1808
- before_document,
1809
- after_document,
1810
- delete_impact
1811
- });
1812
- }
1813
- },
1814
- mongoExplorerDeleteDocument: {
1815
- check: new SimpleSchema({
1816
- database: {
1817
- type: String,
1818
- optional: true
1819
- },
1820
- collection: {
1821
- type: String
1822
- },
1823
- doc_id: {
1824
- type: String
1825
- },
1826
- permissionView: {
1827
- type: String,
1828
- optional: true
1829
- },
1830
- force: {
1831
- type: Boolean,
1832
- optional: true
1833
- },
1834
- mode: {
1835
- type: String,
1836
- optional: true
1837
- }
1838
- }),
1839
- function: async function(database: string, collection: string, doc_id: string, permissionView?: string, force = false, mode?: string) {
1840
- await ensureWriteAccess(this, permissionView, mode);
1841
- const dbName = resolveDatabaseName(database);
1842
- const impact = await buildDeleteImpact(dbName, collection, doc_id);
1843
- if (!force && (impact.unresolved || impact.has_references)) {
1844
- const collectionPreview = impact.collections.slice(0, 3).map(item => item.collection).join(', ');
1845
- if (impact.unresolved) {
1846
- throw new Error('Mongo Explorer: Delete blocked because dependency checks could not complete. Use force delete after review.');
1847
- }
1848
- throw new Error(`Mongo Explorer: Delete blocked. Document is referenced by ${collectionPreview}${impact.collections.length > 3 ? ', ...' : ''}`);
1849
- }
1850
-
1851
- const { managerCollection, dbCollection } = resolveCollectionHandle(dbName, collection);
1852
- const deleteFilter = { _id: doc_id } as any;
1853
-
1854
- if (managerCollection) {
1855
- await managerCollection.deleteOne(deleteFilter);
1856
- }
1857
- else {
1858
- await dbCollection.deleteOne(deleteFilter);
1859
- }
1860
-
1861
- return true;
1862
- }
1863
- },
1864
- mongoExplorerDeleteImpact: {
1865
- check: new SimpleSchema({
1866
- database: {
1867
- type: String,
1868
- optional: true
1869
- },
1870
- collection: {
1871
- type: String
1872
- },
1873
- doc_id: {
1874
- type: String
1875
- }
1876
- }),
1877
- function: async function(database: string, collection: string, doc_id: string) {
1878
- const dbName = resolveDatabaseName(database);
1879
- return buildDeleteImpact(dbName, collection, doc_id);
1880
- }
1881
- }
1882
- });
1883
- }