@resolveio/server-lib 22.2.33 → 22.2.34

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/.github/workflows/ai-assistant-nightly-eval.yml +224 -0
  2. package/.github/workflows/ai-assistant-pr-guardrails.yml +60 -0
  3. package/.nodemon.json +5 -0
  4. package/.vscode/settings.json +21 -0
  5. package/AGENTS.md +179 -0
  6. package/README.md +22 -0
  7. package/build_package.sh +5 -0
  8. package/compileDTS.pl +64 -0
  9. package/docs/ai-assistant-nightly-eval.md +65 -0
  10. package/docs/ai-assistant-preflight-checklist.md +23 -0
  11. package/docs/ai-assistant-report-builder-bridge-playbook.md +115 -0
  12. package/eslint-plugin-custom/index.js +7 -0
  13. package/eslint-plugin-custom/rules/no-filter-zero-index.js +44 -0
  14. package/eslint.config.js +103 -0
  15. package/gulpfile.js +216 -0
  16. package/methodAndPublicationListGenerator.py +319 -0
  17. package/mongodbensurers.js +2 -0
  18. package/mongostop.js +3 -0
  19. package/package.json +1 -1
  20. package/settings.development.json +25 -0
  21. package/settings.development.redacted.json +25 -0
  22. package/src/.env +12 -0
  23. package/src/ai/assistant-core-heuristics.ts +577 -0
  24. package/src/client-server-app.ts +12 -0
  25. package/src/collections/ai-terminal-conversation.collection.ts +91 -0
  26. package/src/collections/ai-terminal-issue-report.collection.ts +99 -0
  27. package/src/collections/ai-terminal-message.collection.ts +77 -0
  28. package/src/collections/app-setting.collection.ts +104 -0
  29. package/src/collections/app-status.collection.ts +58 -0
  30. package/src/collections/communication-metric.collection.ts +84 -0
  31. package/src/collections/counter.collection.ts +56 -0
  32. package/src/collections/cron-job-history.collection.ts +94 -0
  33. package/src/collections/cron-job.collection.ts +92 -0
  34. package/src/collections/customer-notification.collection.ts +131 -0
  35. package/src/collections/customer-portal-password.collection.ts +76 -0
  36. package/src/collections/email-history.collection.ts +121 -0
  37. package/src/collections/email-verified.collection.ts +61 -0
  38. package/src/collections/file.collection.ts +74 -0
  39. package/src/collections/flag-update.collection.ts +57 -0
  40. package/src/collections/flag.collection.ts +57 -0
  41. package/src/collections/log-method-latency.collection.ts +77 -0
  42. package/src/collections/log-subscription.collection.ts +80 -0
  43. package/src/collections/log.collection.ts +93 -0
  44. package/src/collections/logged-in-users.collection.ts +67 -0
  45. package/src/collections/monitor-cpu.collection.ts +65 -0
  46. package/src/collections/monitor-function.collection.ts +74 -0
  47. package/src/collections/monitor-memory.collection.ts +77 -0
  48. package/src/collections/monitor-mongo.collection.ts +71 -0
  49. package/src/collections/notification.collection.ts +57 -0
  50. package/src/collections/openai-usage-ledger.collection.ts +77 -0
  51. package/src/collections/report-builder-dashboard-builder.collection.ts +109 -0
  52. package/src/collections/report-builder-library.collection.ts +89 -0
  53. package/src/collections/report-builder-report.collection.ts +180 -0
  54. package/src/collections/user-group.collection.ts +89 -0
  55. package/src/collections/user-guide.collection.ts +57 -0
  56. package/src/collections/user.collection.ts +181 -0
  57. package/src/cron/cron.ts +117 -0
  58. package/src/fixtures/cron-jobs.ts +95 -0
  59. package/src/fixtures/init.ts +35 -0
  60. package/src/http/auth.ts +764 -0
  61. package/src/http/health.ts +7 -0
  62. package/src/http/home.ts +90 -0
  63. package/src/http/slow-query-publication.ts +49 -0
  64. package/src/index.ts +1 -0
  65. package/src/managers/communication-metric.manager.ts +82 -0
  66. package/src/managers/cron.manager.ts +333 -0
  67. package/src/managers/customer-notification-content.manager.ts +236 -0
  68. package/src/managers/diagnostic-manager-bootstrap.ts +165 -0
  69. package/src/managers/error-auto-fix.manager.ts +2767 -0
  70. package/src/managers/local-log.manager.ts +113 -0
  71. package/src/managers/method.manager.ts +1557 -0
  72. package/src/managers/mongo.manager.ts +4566 -0
  73. package/src/managers/monitor.manager.ts +489 -0
  74. package/src/managers/openai-usage-ledger.manager.ts +116 -0
  75. package/src/managers/slow-query-verifier.manager.ts +3590 -0
  76. package/src/managers/slow-query.manager.ts +519 -0
  77. package/src/managers/subscription.manager.ts +3120 -0
  78. package/src/managers/websocket.manager.ts +746 -0
  79. package/src/managers/worker-dispatcher.manager.ts +1318 -0
  80. package/src/managers/worker-server.manager.ts +468 -0
  81. package/src/methods/accounts.ts +532 -0
  82. package/src/methods/ai-terminal.ts +25505 -0
  83. package/src/methods/app-settings.ts +114 -0
  84. package/src/methods/aws.ts +646 -0
  85. package/src/methods/collections.ts +544 -0
  86. package/src/methods/counters.ts +67 -0
  87. package/src/methods/cron-jobs.ts +2610 -0
  88. package/src/methods/customer-notifications.ts +458 -0
  89. package/src/methods/diagnostics.ts +447 -0
  90. package/src/methods/flag-updates.ts +7 -0
  91. package/src/methods/flags.ts +7 -0
  92. package/src/methods/logs.ts +656 -0
  93. package/src/methods/mongo-explorer.ts +1883 -0
  94. package/src/methods/monitor.ts +540 -0
  95. package/src/methods/pdf.ts +1210 -0
  96. package/src/methods/publications.ts +128 -0
  97. package/src/methods/report-builder.ts +3305 -0
  98. package/src/methods/support.ts +210 -0
  99. package/src/models/ai-terminal-conversation.model.ts +19 -0
  100. package/src/models/ai-terminal-issue-report.model.ts +21 -0
  101. package/src/models/ai-terminal-message.model.ts +24 -0
  102. package/src/models/app-setting.model.ts +17 -0
  103. package/{models/app-status.model.d.ts → src/models/app-status.model.ts} +3 -2
  104. package/{models/billing-logged-in-users.model.d.ts → src/models/billing-logged-in-users.model.ts} +5 -4
  105. package/src/models/collection-document.model.ts +24 -0
  106. package/src/models/communication-metric.model.ts +23 -0
  107. package/{models/counter.model.d.ts → src/models/counter.model.ts} +4 -3
  108. package/src/models/cron-job-history.model.ts +16 -0
  109. package/src/models/cron-job.model.ts +15 -0
  110. package/src/models/customer-notification.model.ts +28 -0
  111. package/src/models/customer-portal-password.model.ts +12 -0
  112. package/src/models/dialog.model.ts +25 -0
  113. package/{models/email-history.model.js → src/models/email-history.model.ts} +34 -4
  114. package/{models/email-verified.model.d.ts → src/models/email-verified.model.ts} +6 -5
  115. package/{models/file.model.d.ts → src/models/file.model.ts} +8 -7
  116. package/{models/flag-update.model.d.ts → src/models/flag-update.model.ts} +4 -3
  117. package/{models/flag.model.d.ts → src/models/flag.model.ts} +4 -3
  118. package/src/models/log-method-latency.model.ts +11 -0
  119. package/{models/log-subscription.model.d.ts → src/models/log-subscription.model.ts} +11 -9
  120. package/src/models/log.model.ts +19 -0
  121. package/{models/logged-in-users.model.d.ts → src/models/logged-in-users.model.ts} +6 -5
  122. package/{models/method-response.model.d.ts → src/models/method-response.model.ts} +7 -6
  123. package/src/models/method.model.ts +23 -0
  124. package/{models/monitor-cpu.model.d.ts → src/models/monitor-cpu.model.ts} +9 -7
  125. package/src/models/monitor-function.model.ts +16 -0
  126. package/src/models/monitor-memory.model.ts +17 -0
  127. package/src/models/monitor-mongo.model.ts +15 -0
  128. package/{models/notification.model.d.ts → src/models/notification.model.ts} +6 -4
  129. package/src/models/openai-usage-ledger.model.ts +16 -0
  130. package/src/models/pagination.model.ts +35 -0
  131. package/src/models/permission.model.ts +14 -0
  132. package/src/models/report-builder-dashboard-builder.model.ts +29 -0
  133. package/src/models/report-builder-library.model.ts +20 -0
  134. package/src/models/report-builder-report.model.ts +135 -0
  135. package/src/models/report-builder.model.ts +68 -0
  136. package/src/models/select-data-label.model.ts +9 -0
  137. package/src/models/server-message.model.ts +31 -0
  138. package/src/models/slow-query-report.model.ts +23 -0
  139. package/src/models/subscription.model.ts +73 -0
  140. package/src/models/support-ticket.model.ts +96 -0
  141. package/src/models/user-group.model.ts +24 -0
  142. package/{models/user-guide.model.d.ts → src/models/user-guide.model.ts} +5 -4
  143. package/src/models/user.model.ts +96 -0
  144. package/src/private/images/ResolveIO.png +0 -0
  145. package/src/publications/ai-terminal.ts +73 -0
  146. package/src/publications/app-settings.ts +25 -0
  147. package/src/publications/app-status.ts +13 -0
  148. package/src/publications/cron-jobs.ts +29 -0
  149. package/src/publications/customer-notifications.ts +101 -0
  150. package/src/publications/files.ts +33 -0
  151. package/src/publications/flags-update.ts +19 -0
  152. package/src/publications/flags.ts +19 -0
  153. package/src/publications/logs.ts +163 -0
  154. package/src/publications/notifications.ts +13 -0
  155. package/src/publications/report-builder-dashboard-builders.ts +39 -0
  156. package/src/publications/report-builder-libraries.ts +41 -0
  157. package/src/publications/report-builder-reports.ts +47 -0
  158. package/src/publications/super-admin.ts +13 -0
  159. package/src/publications/user-groups.ts +12 -0
  160. package/src/publications/user-guides.ts +12 -0
  161. package/src/resolveio-server-app.ts +617 -0
  162. package/src/server-app.ts +2616 -0
  163. package/src/services/codex-client.ts +1117 -0
  164. package/src/services/openai-client.ts +265 -0
  165. package/src/types/error-report.ts +26 -0
  166. package/src/types/js-tiktoken.d.ts +11 -0
  167. package/src/types/slow-query-report.ts +28 -0
  168. package/src/util/common.ts +649 -0
  169. package/src/util/customer-portal-password.ts +183 -0
  170. package/src/util/error-reporter.ts +332 -0
  171. package/src/util/error-tracking.ts +79 -0
  172. package/src/util/report-builder-unwinds.ts +180 -0
  173. package/src/util/schema-report-builder.ts +448 -0
  174. package/src/util/slow-query-reporter.ts +216 -0
  175. package/src/util/subscription-dependency-context.ts +1096 -0
  176. package/src/util/tokenizer.ts +38 -0
  177. package/src/workers/codex-runner.worker.ts +142 -0
  178. package/start_server.sh +5 -0
  179. package/tests/ai-assistant-corpus-build.ts +484 -0
  180. package/tests/ai-assistant-corpus-replay-e2e.ts +773 -0
  181. package/tests/ai-assistant-data-parity-e2e.ts +2018 -0
  182. package/tests/ai-assistant-eval-triage.ts +831 -0
  183. package/tests/ai-assistant-openai-e2e.ts +1061 -0
  184. package/tests/ai-assistant-openai-git-e2e.ts +155 -0
  185. package/tests/ai-assistant-preflight-matrix.ts +215 -0
  186. package/tests/ai-assistant-routing-eval.test.ts +560 -0
  187. package/tests/ai-assistant-snf-live-eval.ts +921 -0
  188. package/tests/ai-assistant-utils.test.ts +2165 -0
  189. package/tests/error-reporter.test.ts +145 -0
  190. package/tests/report-builder-linking.test.ts +79 -0
  191. package/tests/subscription-connect-race.test.ts +157 -0
  192. package/tests/subscription-dependency-context.test.ts +324 -0
  193. package/tests/subscription-manager-collection-tracking.test.ts +86 -0
  194. package/tests/subscription-manager-invalidation.test.ts +85 -0
  195. package/tsconfig.json +34 -0
  196. package/ai/assistant-core-heuristics.d.ts +0 -11
  197. package/ai/assistant-core-heuristics.js +0 -531
  198. package/ai/assistant-core-heuristics.js.map +0 -1
  199. package/client-server-app.d.ts +0 -1
  200. package/client-server-app.js +0 -68
  201. package/client-server-app.js.map +0 -1
  202. package/collections/ai-terminal-conversation.collection.d.ts +0 -2
  203. package/collections/ai-terminal-conversation.collection.js +0 -140
  204. package/collections/ai-terminal-conversation.collection.js.map +0 -1
  205. package/collections/ai-terminal-issue-report.collection.d.ts +0 -2
  206. package/collections/ai-terminal-issue-report.collection.js +0 -148
  207. package/collections/ai-terminal-issue-report.collection.js.map +0 -1
  208. package/collections/ai-terminal-message.collection.d.ts +0 -2
  209. package/collections/ai-terminal-message.collection.js +0 -121
  210. package/collections/ai-terminal-message.collection.js.map +0 -1
  211. package/collections/app-setting.collection.d.ts +0 -3
  212. package/collections/app-setting.collection.js +0 -103
  213. package/collections/app-setting.collection.js.map +0 -1
  214. package/collections/app-status.collection.d.ts +0 -3
  215. package/collections/app-status.collection.js +0 -57
  216. package/collections/app-status.collection.js.map +0 -1
  217. package/collections/communication-metric.collection.d.ts +0 -2
  218. package/collections/communication-metric.collection.js +0 -133
  219. package/collections/communication-metric.collection.js.map +0 -1
  220. package/collections/counter.collection.d.ts +0 -3
  221. package/collections/counter.collection.js +0 -56
  222. package/collections/counter.collection.js.map +0 -1
  223. package/collections/cron-job-history.collection.d.ts +0 -3
  224. package/collections/cron-job-history.collection.js +0 -137
  225. package/collections/cron-job-history.collection.js.map +0 -1
  226. package/collections/cron-job.collection.d.ts +0 -3
  227. package/collections/cron-job.collection.js +0 -92
  228. package/collections/cron-job.collection.js.map +0 -1
  229. package/collections/customer-notification.collection.d.ts +0 -3
  230. package/collections/customer-notification.collection.js +0 -130
  231. package/collections/customer-notification.collection.js.map +0 -1
  232. package/collections/customer-portal-password.collection.d.ts +0 -3
  233. package/collections/customer-portal-password.collection.js +0 -75
  234. package/collections/customer-portal-password.collection.js.map +0 -1
  235. package/collections/email-history.collection.d.ts +0 -3
  236. package/collections/email-history.collection.js +0 -121
  237. package/collections/email-history.collection.js.map +0 -1
  238. package/collections/email-verified.collection.d.ts +0 -3
  239. package/collections/email-verified.collection.js +0 -61
  240. package/collections/email-verified.collection.js.map +0 -1
  241. package/collections/file.collection.d.ts +0 -3
  242. package/collections/file.collection.js +0 -74
  243. package/collections/file.collection.js.map +0 -1
  244. package/collections/flag-update.collection.d.ts +0 -3
  245. package/collections/flag-update.collection.js +0 -57
  246. package/collections/flag-update.collection.js.map +0 -1
  247. package/collections/flag.collection.d.ts +0 -3
  248. package/collections/flag.collection.js +0 -57
  249. package/collections/flag.collection.js.map +0 -1
  250. package/collections/log-method-latency.collection.d.ts +0 -3
  251. package/collections/log-method-latency.collection.js +0 -77
  252. package/collections/log-method-latency.collection.js.map +0 -1
  253. package/collections/log-subscription.collection.d.ts +0 -3
  254. package/collections/log-subscription.collection.js +0 -80
  255. package/collections/log-subscription.collection.js.map +0 -1
  256. package/collections/log.collection.d.ts +0 -3
  257. package/collections/log.collection.js +0 -93
  258. package/collections/log.collection.js.map +0 -1
  259. package/collections/logged-in-users.collection.d.ts +0 -3
  260. package/collections/logged-in-users.collection.js +0 -67
  261. package/collections/logged-in-users.collection.js.map +0 -1
  262. package/collections/monitor-cpu.collection.d.ts +0 -3
  263. package/collections/monitor-cpu.collection.js +0 -65
  264. package/collections/monitor-cpu.collection.js.map +0 -1
  265. package/collections/monitor-function.collection.d.ts +0 -3
  266. package/collections/monitor-function.collection.js +0 -74
  267. package/collections/monitor-function.collection.js.map +0 -1
  268. package/collections/monitor-memory.collection.d.ts +0 -3
  269. package/collections/monitor-memory.collection.js +0 -77
  270. package/collections/monitor-memory.collection.js.map +0 -1
  271. package/collections/monitor-mongo.collection.d.ts +0 -3
  272. package/collections/monitor-mongo.collection.js +0 -71
  273. package/collections/monitor-mongo.collection.js.map +0 -1
  274. package/collections/notification.collection.d.ts +0 -3
  275. package/collections/notification.collection.js +0 -57
  276. package/collections/notification.collection.js.map +0 -1
  277. package/collections/openai-usage-ledger.collection.d.ts +0 -2
  278. package/collections/openai-usage-ledger.collection.js +0 -124
  279. package/collections/openai-usage-ledger.collection.js.map +0 -1
  280. package/collections/report-builder-dashboard-builder.collection.d.ts +0 -3
  281. package/collections/report-builder-dashboard-builder.collection.js +0 -109
  282. package/collections/report-builder-dashboard-builder.collection.js.map +0 -1
  283. package/collections/report-builder-library.collection.d.ts +0 -3
  284. package/collections/report-builder-library.collection.js +0 -87
  285. package/collections/report-builder-library.collection.js.map +0 -1
  286. package/collections/report-builder-report.collection.d.ts +0 -4
  287. package/collections/report-builder-report.collection.js +0 -180
  288. package/collections/report-builder-report.collection.js.map +0 -1
  289. package/collections/user-group.collection.d.ts +0 -4
  290. package/collections/user-group.collection.js +0 -89
  291. package/collections/user-group.collection.js.map +0 -1
  292. package/collections/user-guide.collection.d.ts +0 -3
  293. package/collections/user-guide.collection.js +0 -57
  294. package/collections/user-guide.collection.js.map +0 -1
  295. package/collections/user.collection.d.ts +0 -4
  296. package/collections/user.collection.js +0 -180
  297. package/collections/user.collection.js.map +0 -1
  298. package/cron/cron.d.ts +0 -14
  299. package/cron/cron.js +0 -216
  300. package/cron/cron.js.map +0 -1
  301. package/fixtures/cron-jobs.d.ts +0 -1
  302. package/fixtures/cron-jobs.js +0 -150
  303. package/fixtures/cron-jobs.js.map +0 -1
  304. package/fixtures/init.d.ts +0 -1
  305. package/fixtures/init.js +0 -91
  306. package/fixtures/init.js.map +0 -1
  307. package/http/auth.d.ts +0 -2
  308. package/http/auth.js +0 -903
  309. package/http/auth.js.map +0 -1
  310. package/http/health.d.ts +0 -1
  311. package/http/health.js +0 -11
  312. package/http/health.js.map +0 -1
  313. package/http/home.d.ts +0 -1
  314. package/http/home.js +0 -134
  315. package/http/home.js.map +0 -1
  316. package/http/slow-query-publication.d.ts +0 -2
  317. package/http/slow-query-publication.js +0 -99
  318. package/http/slow-query-publication.js.map +0 -1
  319. package/index.d.ts +0 -1
  320. package/index.js +0 -19
  321. package/index.js.map +0 -1
  322. package/managers/communication-metric.manager.d.ts +0 -16
  323. package/managers/communication-metric.manager.js +0 -134
  324. package/managers/communication-metric.manager.js.map +0 -1
  325. package/managers/cron.manager.d.ts +0 -20
  326. package/managers/cron.manager.js +0 -534
  327. package/managers/cron.manager.js.map +0 -1
  328. package/managers/customer-notification-content.manager.d.ts +0 -55
  329. package/managers/customer-notification-content.manager.js +0 -158
  330. package/managers/customer-notification-content.manager.js.map +0 -1
  331. package/managers/diagnostic-manager-bootstrap.d.ts +0 -9
  332. package/managers/diagnostic-manager-bootstrap.js +0 -260
  333. package/managers/diagnostic-manager-bootstrap.js.map +0 -1
  334. package/managers/error-auto-fix.manager.d.ts +0 -149
  335. package/managers/error-auto-fix.manager.js +0 -3064
  336. package/managers/error-auto-fix.manager.js.map +0 -1
  337. package/managers/local-log.manager.d.ts +0 -18
  338. package/managers/local-log.manager.js +0 -88
  339. package/managers/local-log.manager.js.map +0 -1
  340. package/managers/method.manager.d.ts +0 -77
  341. package/managers/method.manager.js +0 -1701
  342. package/managers/method.manager.js.map +0 -1
  343. package/managers/mongo.manager.d.ts +0 -222
  344. package/managers/mongo.manager.js +0 -4984
  345. package/managers/mongo.manager.js.map +0 -1
  346. package/managers/monitor.manager.d.ts +0 -69
  347. package/managers/monitor.manager.js +0 -534
  348. package/managers/monitor.manager.js.map +0 -1
  349. package/managers/openai-usage-ledger.manager.d.ts +0 -15
  350. package/managers/openai-usage-ledger.manager.js +0 -144
  351. package/managers/openai-usage-ledger.manager.js.map +0 -1
  352. package/managers/slow-query-verifier.manager.d.ts +0 -144
  353. package/managers/slow-query-verifier.manager.js +0 -3857
  354. package/managers/slow-query-verifier.manager.js.map +0 -1
  355. package/managers/slow-query.manager.d.ts +0 -28
  356. package/managers/slow-query.manager.js +0 -468
  357. package/managers/slow-query.manager.js.map +0 -1
  358. package/managers/subscription.manager.d.ts +0 -169
  359. package/managers/subscription.manager.js +0 -3422
  360. package/managers/subscription.manager.js.map +0 -1
  361. package/managers/websocket.manager.d.ts +0 -73
  362. package/managers/websocket.manager.js +0 -673
  363. package/managers/websocket.manager.js.map +0 -1
  364. package/managers/worker-dispatcher.manager.d.ts +0 -117
  365. package/managers/worker-dispatcher.manager.js +0 -1210
  366. package/managers/worker-dispatcher.manager.js.map +0 -1
  367. package/managers/worker-server.manager.d.ts +0 -16
  368. package/managers/worker-server.manager.js +0 -530
  369. package/managers/worker-server.manager.js.map +0 -1
  370. package/methods/accounts.d.ts +0 -2
  371. package/methods/accounts.js +0 -624
  372. package/methods/accounts.js.map +0 -1
  373. package/methods/ai-terminal.d.ts +0 -304
  374. package/methods/ai-terminal.js +0 -25096
  375. package/methods/ai-terminal.js.map +0 -1
  376. package/methods/app-settings.d.ts +0 -2
  377. package/methods/app-settings.js +0 -169
  378. package/methods/app-settings.js.map +0 -1
  379. package/methods/aws.d.ts +0 -2
  380. package/methods/aws.js +0 -874
  381. package/methods/aws.js.map +0 -1
  382. package/methods/collections.d.ts +0 -2
  383. package/methods/collections.js +0 -626
  384. package/methods/collections.js.map +0 -1
  385. package/methods/counters.d.ts +0 -2
  386. package/methods/counters.js +0 -111
  387. package/methods/counters.js.map +0 -1
  388. package/methods/cron-jobs.d.ts +0 -2
  389. package/methods/cron-jobs.js +0 -2471
  390. package/methods/cron-jobs.js.map +0 -1
  391. package/methods/customer-notifications.d.ts +0 -2
  392. package/methods/customer-notifications.js +0 -528
  393. package/methods/customer-notifications.js.map +0 -1
  394. package/methods/diagnostics.d.ts +0 -2
  395. package/methods/diagnostics.js +0 -514
  396. package/methods/diagnostics.js.map +0 -1
  397. package/methods/flag-updates.d.ts +0 -2
  398. package/methods/flag-updates.js +0 -8
  399. package/methods/flag-updates.js.map +0 -1
  400. package/methods/flags.d.ts +0 -2
  401. package/methods/flags.js +0 -8
  402. package/methods/flags.js.map +0 -1
  403. package/methods/logs.d.ts +0 -2
  404. package/methods/logs.js +0 -750
  405. package/methods/logs.js.map +0 -1
  406. package/methods/mongo-explorer.d.ts +0 -2
  407. package/methods/mongo-explorer.js +0 -1811
  408. package/methods/mongo-explorer.js.map +0 -1
  409. package/methods/monitor.d.ts +0 -2
  410. package/methods/monitor.js +0 -543
  411. package/methods/monitor.js.map +0 -1
  412. package/methods/pdf.d.ts +0 -2
  413. package/methods/pdf.js +0 -1195
  414. package/methods/pdf.js.map +0 -1
  415. package/methods/publications.d.ts +0 -1
  416. package/methods/publications.js +0 -183
  417. package/methods/publications.js.map +0 -1
  418. package/methods/report-builder.d.ts +0 -2
  419. package/methods/report-builder.js +0 -2960
  420. package/methods/report-builder.js.map +0 -1
  421. package/methods/support.d.ts +0 -2
  422. package/methods/support.js +0 -313
  423. package/methods/support.js.map +0 -1
  424. package/models/ai-terminal-conversation.model.d.ts +0 -17
  425. package/models/ai-terminal-conversation.model.js +0 -4
  426. package/models/ai-terminal-conversation.model.js.map +0 -1
  427. package/models/ai-terminal-issue-report.model.d.ts +0 -19
  428. package/models/ai-terminal-issue-report.model.js +0 -4
  429. package/models/ai-terminal-issue-report.model.js.map +0 -1
  430. package/models/ai-terminal-message.model.d.ts +0 -22
  431. package/models/ai-terminal-message.model.js +0 -4
  432. package/models/ai-terminal-message.model.js.map +0 -1
  433. package/models/app-setting.model.d.ts +0 -16
  434. package/models/app-setting.model.js +0 -4
  435. package/models/app-setting.model.js.map +0 -1
  436. package/models/app-status.model.js +0 -4
  437. package/models/app-status.model.js.map +0 -1
  438. package/models/billing-logged-in-users.model.js +0 -4
  439. package/models/billing-logged-in-users.model.js.map +0 -1
  440. package/models/collection-document.model.d.ts +0 -21
  441. package/models/collection-document.model.js +0 -4
  442. package/models/collection-document.model.js.map +0 -1
  443. package/models/communication-metric.model.d.ts +0 -20
  444. package/models/communication-metric.model.js +0 -4
  445. package/models/communication-metric.model.js.map +0 -1
  446. package/models/counter.model.js +0 -4
  447. package/models/counter.model.js.map +0 -1
  448. package/models/cron-job-history.model.d.ts +0 -15
  449. package/models/cron-job-history.model.js +0 -4
  450. package/models/cron-job-history.model.js.map +0 -1
  451. package/models/cron-job.model.d.ts +0 -14
  452. package/models/cron-job.model.js +0 -4
  453. package/models/cron-job.model.js.map +0 -1
  454. package/models/customer-notification.model.d.ts +0 -26
  455. package/models/customer-notification.model.js +0 -4
  456. package/models/customer-notification.model.js.map +0 -1
  457. package/models/customer-portal-password.model.d.ts +0 -11
  458. package/models/customer-portal-password.model.js +0 -4
  459. package/models/customer-portal-password.model.js.map +0 -1
  460. package/models/dialog.model.d.ts +0 -23
  461. package/models/dialog.model.js +0 -4
  462. package/models/dialog.model.js.map +0 -1
  463. package/models/email-history.model.d.ts +0 -30
  464. package/models/email-history.model.js.map +0 -1
  465. package/models/email-verified.model.js +0 -4
  466. package/models/email-verified.model.js.map +0 -1
  467. package/models/file.model.js +0 -4
  468. package/models/file.model.js.map +0 -1
  469. package/models/flag-update.model.js +0 -4
  470. package/models/flag-update.model.js.map +0 -1
  471. package/models/flag.model.js +0 -4
  472. package/models/flag.model.js.map +0 -1
  473. package/models/log-method-latency.model.d.ts +0 -10
  474. package/models/log-method-latency.model.js +0 -4
  475. package/models/log-method-latency.model.js.map +0 -1
  476. package/models/log-subscription.model.js +0 -4
  477. package/models/log-subscription.model.js.map +0 -1
  478. package/models/log.model.d.ts +0 -17
  479. package/models/log.model.js +0 -4
  480. package/models/log.model.js.map +0 -1
  481. package/models/logged-in-users.model.js +0 -4
  482. package/models/logged-in-users.model.js.map +0 -1
  483. package/models/method-response.model.js +0 -4
  484. package/models/method-response.model.js.map +0 -1
  485. package/models/method.model.d.ts +0 -24
  486. package/models/method.model.js +0 -4
  487. package/models/method.model.js.map +0 -1
  488. package/models/monitor-cpu.model.js +0 -4
  489. package/models/monitor-cpu.model.js.map +0 -1
  490. package/models/monitor-function.model.d.ts +0 -14
  491. package/models/monitor-function.model.js +0 -4
  492. package/models/monitor-function.model.js.map +0 -1
  493. package/models/monitor-memory.model.d.ts +0 -15
  494. package/models/monitor-memory.model.js +0 -4
  495. package/models/monitor-memory.model.js.map +0 -1
  496. package/models/monitor-mongo.model.d.ts +0 -13
  497. package/models/monitor-mongo.model.js +0 -4
  498. package/models/monitor-mongo.model.js.map +0 -1
  499. package/models/notification.model.js +0 -4
  500. package/models/notification.model.js.map +0 -1
  501. package/models/openai-usage-ledger.model.d.ts +0 -15
  502. package/models/openai-usage-ledger.model.js +0 -4
  503. package/models/openai-usage-ledger.model.js.map +0 -1
  504. package/models/pagination.model.d.ts +0 -11
  505. package/models/pagination.model.js +0 -28
  506. package/models/pagination.model.js.map +0 -1
  507. package/models/permission.model.d.ts +0 -12
  508. package/models/permission.model.js +0 -4
  509. package/models/permission.model.js.map +0 -1
  510. package/models/report-builder-dashboard-builder.model.d.ts +0 -25
  511. package/models/report-builder-dashboard-builder.model.js +0 -4
  512. package/models/report-builder-dashboard-builder.model.js.map +0 -1
  513. package/models/report-builder-library.model.d.ts +0 -17
  514. package/models/report-builder-library.model.js +0 -4
  515. package/models/report-builder-library.model.js.map +0 -1
  516. package/models/report-builder-report.model.d.ts +0 -120
  517. package/models/report-builder-report.model.js +0 -4
  518. package/models/report-builder-report.model.js.map +0 -1
  519. package/models/report-builder.model.d.ts +0 -61
  520. package/models/report-builder.model.js +0 -4
  521. package/models/report-builder.model.js.map +0 -1
  522. package/models/select-data-label.model.d.ts +0 -9
  523. package/models/select-data-label.model.js +0 -4
  524. package/models/select-data-label.model.js.map +0 -1
  525. package/models/server-message.model.d.ts +0 -32
  526. package/models/server-message.model.js +0 -4
  527. package/models/server-message.model.js.map +0 -1
  528. package/models/slow-query-report.model.d.ts +0 -23
  529. package/models/slow-query-report.model.js +0 -4
  530. package/models/slow-query-report.model.js.map +0 -1
  531. package/models/subscription.model.d.ts +0 -31
  532. package/models/subscription.model.js +0 -4
  533. package/models/subscription.model.js.map +0 -1
  534. package/models/support-ticket.model.d.ts +0 -86
  535. package/models/support-ticket.model.js +0 -4
  536. package/models/support-ticket.model.js.map +0 -1
  537. package/models/user-group.model.d.ts +0 -20
  538. package/models/user-group.model.js +0 -4
  539. package/models/user-group.model.js.map +0 -1
  540. package/models/user-guide.model.js +0 -4
  541. package/models/user-guide.model.js.map +0 -1
  542. package/models/user.model.d.ts +0 -84
  543. package/models/user.model.js +0 -4
  544. package/models/user.model.js.map +0 -1
  545. package/private/images/ResolveIO.png +0 -0
  546. package/public_api.js +0 -107
  547. package/public_api.js.map +0 -1
  548. package/publications/ai-terminal.d.ts +0 -1
  549. package/publications/ai-terminal.js +0 -122
  550. package/publications/ai-terminal.js.map +0 -1
  551. package/publications/app-settings.d.ts +0 -2
  552. package/publications/app-settings.js +0 -28
  553. package/publications/app-settings.js.map +0 -1
  554. package/publications/app-status.d.ts +0 -2
  555. package/publications/app-status.js +0 -16
  556. package/publications/app-status.js.map +0 -1
  557. package/publications/cron-jobs.d.ts +0 -2
  558. package/publications/cron-jobs.js +0 -32
  559. package/publications/cron-jobs.js.map +0 -1
  560. package/publications/customer-notifications.d.ts +0 -2
  561. package/publications/customer-notifications.js +0 -161
  562. package/publications/customer-notifications.js.map +0 -1
  563. package/publications/files.d.ts +0 -2
  564. package/publications/files.js +0 -36
  565. package/publications/files.js.map +0 -1
  566. package/publications/flags-update.d.ts +0 -2
  567. package/publications/flags-update.js +0 -22
  568. package/publications/flags-update.js.map +0 -1
  569. package/publications/flags.d.ts +0 -2
  570. package/publications/flags.js +0 -22
  571. package/publications/flags.js.map +0 -1
  572. package/publications/logs.d.ts +0 -2
  573. package/publications/logs.js +0 -164
  574. package/publications/logs.js.map +0 -1
  575. package/publications/notifications.d.ts +0 -2
  576. package/publications/notifications.js +0 -16
  577. package/publications/notifications.js.map +0 -1
  578. package/publications/report-builder-dashboard-builders.d.ts +0 -2
  579. package/publications/report-builder-dashboard-builders.js +0 -42
  580. package/publications/report-builder-dashboard-builders.js.map +0 -1
  581. package/publications/report-builder-libraries.d.ts +0 -2
  582. package/publications/report-builder-libraries.js +0 -90
  583. package/publications/report-builder-libraries.js.map +0 -1
  584. package/publications/report-builder-reports.d.ts +0 -2
  585. package/publications/report-builder-reports.js +0 -50
  586. package/publications/report-builder-reports.js.map +0 -1
  587. package/publications/super-admin.d.ts +0 -2
  588. package/publications/super-admin.js +0 -16
  589. package/publications/super-admin.js.map +0 -1
  590. package/publications/user-groups.d.ts +0 -1
  591. package/publications/user-groups.js +0 -16
  592. package/publications/user-groups.js.map +0 -1
  593. package/publications/user-guides.d.ts +0 -1
  594. package/publications/user-guides.js +0 -16
  595. package/publications/user-guides.js.map +0 -1
  596. package/resolveio-server-app.d.ts +0 -70
  597. package/resolveio-server-app.js +0 -801
  598. package/resolveio-server-app.js.map +0 -1
  599. package/server-app.d.ts +0 -167
  600. package/server-app.js +0 -2784
  601. package/server-app.js.map +0 -1
  602. package/services/codex-client.d.ts +0 -119
  603. package/services/codex-client.js +0 -1470
  604. package/services/codex-client.js.map +0 -1
  605. package/services/openai-client.d.ts +0 -46
  606. package/services/openai-client.js +0 -318
  607. package/services/openai-client.js.map +0 -1
  608. package/types/error-report.d.ts +0 -25
  609. package/types/error-report.js +0 -4
  610. package/types/error-report.js.map +0 -1
  611. package/types/slow-query-report.d.ts +0 -27
  612. package/types/slow-query-report.js +0 -6
  613. package/types/slow-query-report.js.map +0 -1
  614. package/util/common.d.ts +0 -31
  615. package/util/common.js +0 -683
  616. package/util/common.js.map +0 -1
  617. package/util/customer-portal-password.d.ts +0 -13
  618. package/util/customer-portal-password.js +0 -209
  619. package/util/customer-portal-password.js.map +0 -1
  620. package/util/error-reporter.d.ts +0 -52
  621. package/util/error-reporter.js +0 -326
  622. package/util/error-reporter.js.map +0 -1
  623. package/util/error-tracking.d.ts +0 -13
  624. package/util/error-tracking.js +0 -120
  625. package/util/error-tracking.js.map +0 -1
  626. package/util/report-builder-unwinds.d.ts +0 -15
  627. package/util/report-builder-unwinds.js +0 -156
  628. package/util/report-builder-unwinds.js.map +0 -1
  629. package/util/schema-report-builder.d.ts +0 -6
  630. package/util/schema-report-builder.js +0 -481
  631. package/util/schema-report-builder.js.map +0 -1
  632. package/util/slow-query-reporter.d.ts +0 -28
  633. package/util/slow-query-reporter.js +0 -226
  634. package/util/slow-query-reporter.js.map +0 -1
  635. package/util/subscription-dependency-context.d.ts +0 -34
  636. package/util/subscription-dependency-context.js +0 -1283
  637. package/util/subscription-dependency-context.js.map +0 -1
  638. package/util/tokenizer.d.ts +0 -5
  639. package/util/tokenizer.js +0 -41
  640. package/util/tokenizer.js.map +0 -1
  641. package/workers/codex-runner.worker.d.ts +0 -1
  642. package/workers/codex-runner.worker.js +0 -192
  643. package/workers/codex-runner.worker.js.map +0 -1
  644. /package/{private → src/private}/email-templates/enrollment.html +0 -0
  645. /package/{private → src/private}/email-templates/forgot-password.html +0 -0
  646. /package/{private → src/private}/email-templates/support-ticket-deleted.html +0 -0
  647. /package/{private → src/private}/email-templates/support-ticket-modified.html +0 -0
  648. /package/{private → src/private}/email-templates/support-ticket.html +0 -0
  649. /package/{public_api.d.ts → src/public_api.ts} +0 -0
@@ -1,1811 +0,0 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
- var __read = (this && this.__read) || function (o, n) {
50
- var m = typeof Symbol === "function" && o[Symbol.iterator];
51
- if (!m) return o;
52
- var i = m.call(o), r, ar = [], e;
53
- try {
54
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
- }
56
- catch (error) { e = { error: error }; }
57
- finally {
58
- try {
59
- if (r && !r.done && (m = i["return"])) m.call(i);
60
- }
61
- finally { if (e) throw e.error; }
62
- }
63
- return ar;
64
- };
65
- var __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