@resolveio/server-lib 22.2.34 → 22.2.35

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