@depup/mongodb 7.1.0-depup.0

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 (396) hide show
  1. package/LICENSE.md +201 -0
  2. package/README.md +33 -0
  3. package/etc/prepare.js +12 -0
  4. package/lib/admin.js +136 -0
  5. package/lib/admin.js.map +1 -0
  6. package/lib/bson.js +85 -0
  7. package/lib/bson.js.map +1 -0
  8. package/lib/bulk/common.js +835 -0
  9. package/lib/bulk/common.js.map +1 -0
  10. package/lib/bulk/ordered.js +67 -0
  11. package/lib/bulk/ordered.js.map +1 -0
  12. package/lib/bulk/unordered.js +92 -0
  13. package/lib/bulk/unordered.js.map +1 -0
  14. package/lib/change_stream.js +513 -0
  15. package/lib/change_stream.js.map +1 -0
  16. package/lib/client-side-encryption/auto_encrypter.js +272 -0
  17. package/lib/client-side-encryption/auto_encrypter.js.map +1 -0
  18. package/lib/client-side-encryption/client_encryption.js +609 -0
  19. package/lib/client-side-encryption/client_encryption.js.map +1 -0
  20. package/lib/client-side-encryption/errors.js +138 -0
  21. package/lib/client-side-encryption/errors.js.map +1 -0
  22. package/lib/client-side-encryption/mongocryptd_manager.js +85 -0
  23. package/lib/client-side-encryption/mongocryptd_manager.js.map +1 -0
  24. package/lib/client-side-encryption/providers/aws.js +23 -0
  25. package/lib/client-side-encryption/providers/aws.js.map +1 -0
  26. package/lib/client-side-encryption/providers/azure.js +132 -0
  27. package/lib/client-side-encryption/providers/azure.js.map +1 -0
  28. package/lib/client-side-encryption/providers/gcp.js +16 -0
  29. package/lib/client-side-encryption/providers/gcp.js.map +1 -0
  30. package/lib/client-side-encryption/providers/index.js +43 -0
  31. package/lib/client-side-encryption/providers/index.js.map +1 -0
  32. package/lib/client-side-encryption/state_machine.js +427 -0
  33. package/lib/client-side-encryption/state_machine.js.map +1 -0
  34. package/lib/cmap/auth/auth_provider.js +51 -0
  35. package/lib/cmap/auth/auth_provider.js.map +1 -0
  36. package/lib/cmap/auth/aws4.js +161 -0
  37. package/lib/cmap/auth/aws4.js.map +1 -0
  38. package/lib/cmap/auth/aws_temporary_credentials.js +103 -0
  39. package/lib/cmap/auth/aws_temporary_credentials.js.map +1 -0
  40. package/lib/cmap/auth/gssapi.js +155 -0
  41. package/lib/cmap/auth/gssapi.js.map +1 -0
  42. package/lib/cmap/auth/mongo_credentials.js +169 -0
  43. package/lib/cmap/auth/mongo_credentials.js.map +1 -0
  44. package/lib/cmap/auth/mongodb_aws.js +128 -0
  45. package/lib/cmap/auth/mongodb_aws.js.map +1 -0
  46. package/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js +84 -0
  47. package/lib/cmap/auth/mongodb_oidc/automated_callback_workflow.js.map +1 -0
  48. package/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js +62 -0
  49. package/lib/cmap/auth/mongodb_oidc/azure_machine_workflow.js.map +1 -0
  50. package/lib/cmap/auth/mongodb_oidc/callback_workflow.js +141 -0
  51. package/lib/cmap/auth/mongodb_oidc/callback_workflow.js.map +1 -0
  52. package/lib/cmap/auth/mongodb_oidc/command_builders.js +44 -0
  53. package/lib/cmap/auth/mongodb_oidc/command_builders.js.map +1 -0
  54. package/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js +39 -0
  55. package/lib/cmap/auth/mongodb_oidc/gcp_machine_workflow.js.map +1 -0
  56. package/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js +122 -0
  57. package/lib/cmap/auth/mongodb_oidc/human_callback_workflow.js.map +1 -0
  58. package/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js +32 -0
  59. package/lib/cmap/auth/mongodb_oidc/k8s_machine_workflow.js.map +1 -0
  60. package/lib/cmap/auth/mongodb_oidc/token_cache.js +52 -0
  61. package/lib/cmap/auth/mongodb_oidc/token_cache.js.map +1 -0
  62. package/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js +23 -0
  63. package/lib/cmap/auth/mongodb_oidc/token_machine_workflow.js.map +1 -0
  64. package/lib/cmap/auth/mongodb_oidc.js +73 -0
  65. package/lib/cmap/auth/mongodb_oidc.js.map +1 -0
  66. package/lib/cmap/auth/plain.js +26 -0
  67. package/lib/cmap/auth/plain.js.map +1 -0
  68. package/lib/cmap/auth/providers.js +22 -0
  69. package/lib/cmap/auth/providers.js.map +1 -0
  70. package/lib/cmap/auth/scram.js +254 -0
  71. package/lib/cmap/auth/scram.js.map +1 -0
  72. package/lib/cmap/auth/x509.js +36 -0
  73. package/lib/cmap/auth/x509.js.map +1 -0
  74. package/lib/cmap/command_monitoring_events.js +223 -0
  75. package/lib/cmap/command_monitoring_events.js.map +1 -0
  76. package/lib/cmap/commands.js +535 -0
  77. package/lib/cmap/commands.js.map +1 -0
  78. package/lib/cmap/connect.js +381 -0
  79. package/lib/cmap/connect.js.map +1 -0
  80. package/lib/cmap/connection.js +571 -0
  81. package/lib/cmap/connection.js.map +1 -0
  82. package/lib/cmap/connection_pool.js +558 -0
  83. package/lib/cmap/connection_pool.js.map +1 -0
  84. package/lib/cmap/connection_pool_events.js +190 -0
  85. package/lib/cmap/connection_pool_events.js.map +1 -0
  86. package/lib/cmap/errors.js +108 -0
  87. package/lib/cmap/errors.js.map +1 -0
  88. package/lib/cmap/handshake/client_metadata.js +242 -0
  89. package/lib/cmap/handshake/client_metadata.js.map +1 -0
  90. package/lib/cmap/metrics.js +62 -0
  91. package/lib/cmap/metrics.js.map +1 -0
  92. package/lib/cmap/stream_description.js +70 -0
  93. package/lib/cmap/stream_description.js.map +1 -0
  94. package/lib/cmap/wire_protocol/compression.js +178 -0
  95. package/lib/cmap/wire_protocol/compression.js.map +1 -0
  96. package/lib/cmap/wire_protocol/constants.js +21 -0
  97. package/lib/cmap/wire_protocol/constants.js.map +1 -0
  98. package/lib/cmap/wire_protocol/on_data.js +111 -0
  99. package/lib/cmap/wire_protocol/on_data.js.map +1 -0
  100. package/lib/cmap/wire_protocol/on_demand/document.js +222 -0
  101. package/lib/cmap/wire_protocol/on_demand/document.js.map +1 -0
  102. package/lib/cmap/wire_protocol/responses.js +315 -0
  103. package/lib/cmap/wire_protocol/responses.js.map +1 -0
  104. package/lib/cmap/wire_protocol/shared.js +35 -0
  105. package/lib/cmap/wire_protocol/shared.js.map +1 -0
  106. package/lib/collection.js +751 -0
  107. package/lib/collection.js.map +1 -0
  108. package/lib/connection_string.js +1090 -0
  109. package/lib/connection_string.js.map +1 -0
  110. package/lib/constants.js +170 -0
  111. package/lib/constants.js.map +1 -0
  112. package/lib/cursor/abstract_cursor.js +924 -0
  113. package/lib/cursor/abstract_cursor.js.map +1 -0
  114. package/lib/cursor/aggregation_cursor.js +164 -0
  115. package/lib/cursor/aggregation_cursor.js.map +1 -0
  116. package/lib/cursor/change_stream_cursor.js +104 -0
  117. package/lib/cursor/change_stream_cursor.js.map +1 -0
  118. package/lib/cursor/client_bulk_write_cursor.js +52 -0
  119. package/lib/cursor/client_bulk_write_cursor.js.map +1 -0
  120. package/lib/cursor/explainable_cursor.js +36 -0
  121. package/lib/cursor/explainable_cursor.js.map +1 -0
  122. package/lib/cursor/find_cursor.js +399 -0
  123. package/lib/cursor/find_cursor.js.map +1 -0
  124. package/lib/cursor/list_collections_cursor.js +34 -0
  125. package/lib/cursor/list_collections_cursor.js.map +1 -0
  126. package/lib/cursor/list_indexes_cursor.js +32 -0
  127. package/lib/cursor/list_indexes_cursor.js.map +1 -0
  128. package/lib/cursor/list_search_indexes_cursor.js +14 -0
  129. package/lib/cursor/list_search_indexes_cursor.js.map +1 -0
  130. package/lib/cursor/run_command_cursor.js +94 -0
  131. package/lib/cursor/run_command_cursor.js.map +1 -0
  132. package/lib/db.js +419 -0
  133. package/lib/db.js.map +1 -0
  134. package/lib/deps.js +112 -0
  135. package/lib/deps.js.map +1 -0
  136. package/lib/encrypter.js +106 -0
  137. package/lib/encrypter.js.map +1 -0
  138. package/lib/error.js +1380 -0
  139. package/lib/error.js.map +1 -0
  140. package/lib/explain.js +59 -0
  141. package/lib/explain.js.map +1 -0
  142. package/lib/gridfs/download.js +305 -0
  143. package/lib/gridfs/download.js.map +1 -0
  144. package/lib/gridfs/index.js +164 -0
  145. package/lib/gridfs/index.js.map +1 -0
  146. package/lib/gridfs/upload.js +358 -0
  147. package/lib/gridfs/upload.js.map +1 -0
  148. package/lib/index.js +193 -0
  149. package/lib/index.js.map +1 -0
  150. package/lib/mongo_client.js +557 -0
  151. package/lib/mongo_client.js.map +1 -0
  152. package/lib/mongo_client_auth_providers.js +80 -0
  153. package/lib/mongo_client_auth_providers.js.map +1 -0
  154. package/lib/mongo_logger.js +655 -0
  155. package/lib/mongo_logger.js.map +1 -0
  156. package/lib/mongo_types.js +56 -0
  157. package/lib/mongo_types.js.map +1 -0
  158. package/lib/operations/aggregate.js +90 -0
  159. package/lib/operations/aggregate.js.map +1 -0
  160. package/lib/operations/client_bulk_write/client_bulk_write.js +51 -0
  161. package/lib/operations/client_bulk_write/client_bulk_write.js.map +1 -0
  162. package/lib/operations/client_bulk_write/command_builder.js +340 -0
  163. package/lib/operations/client_bulk_write/command_builder.js.map +1 -0
  164. package/lib/operations/client_bulk_write/common.js +3 -0
  165. package/lib/operations/client_bulk_write/common.js.map +1 -0
  166. package/lib/operations/client_bulk_write/executor.js +120 -0
  167. package/lib/operations/client_bulk_write/executor.js.map +1 -0
  168. package/lib/operations/client_bulk_write/results_merger.js +204 -0
  169. package/lib/operations/client_bulk_write/results_merger.js.map +1 -0
  170. package/lib/operations/command.js +83 -0
  171. package/lib/operations/command.js.map +1 -0
  172. package/lib/operations/count.js +45 -0
  173. package/lib/operations/count.js.map +1 -0
  174. package/lib/operations/create_collection.js +109 -0
  175. package/lib/operations/create_collection.js.map +1 -0
  176. package/lib/operations/delete.js +125 -0
  177. package/lib/operations/delete.js.map +1 -0
  178. package/lib/operations/distinct.js +61 -0
  179. package/lib/operations/distinct.js.map +1 -0
  180. package/lib/operations/drop.js +93 -0
  181. package/lib/operations/drop.js.map +1 -0
  182. package/lib/operations/end_sessions.js +34 -0
  183. package/lib/operations/end_sessions.js.map +1 -0
  184. package/lib/operations/estimated_document_count.js +41 -0
  185. package/lib/operations/estimated_document_count.js.map +1 -0
  186. package/lib/operations/execute_operation.js +239 -0
  187. package/lib/operations/execute_operation.js.map +1 -0
  188. package/lib/operations/find.js +148 -0
  189. package/lib/operations/find.js.map +1 -0
  190. package/lib/operations/find_and_modify.js +158 -0
  191. package/lib/operations/find_and_modify.js.map +1 -0
  192. package/lib/operations/get_more.js +62 -0
  193. package/lib/operations/get_more.js.map +1 -0
  194. package/lib/operations/indexes.js +186 -0
  195. package/lib/operations/indexes.js.map +1 -0
  196. package/lib/operations/insert.js +70 -0
  197. package/lib/operations/insert.js.map +1 -0
  198. package/lib/operations/kill_cursors.js +43 -0
  199. package/lib/operations/kill_cursors.js.map +1 -0
  200. package/lib/operations/list_collections.js +53 -0
  201. package/lib/operations/list_collections.js.map +1 -0
  202. package/lib/operations/list_databases.js +40 -0
  203. package/lib/operations/list_databases.js.map +1 -0
  204. package/lib/operations/operation.js +102 -0
  205. package/lib/operations/operation.js.map +1 -0
  206. package/lib/operations/profiling_level.js +43 -0
  207. package/lib/operations/profiling_level.js.map +1 -0
  208. package/lib/operations/remove_user.js +27 -0
  209. package/lib/operations/remove_user.js.map +1 -0
  210. package/lib/operations/rename.js +38 -0
  211. package/lib/operations/rename.js.map +1 -0
  212. package/lib/operations/run_command.js +47 -0
  213. package/lib/operations/run_command.js.map +1 -0
  214. package/lib/operations/search_indexes/create.js +33 -0
  215. package/lib/operations/search_indexes/create.js.map +1 -0
  216. package/lib/operations/search_indexes/drop.js +43 -0
  217. package/lib/operations/search_indexes/drop.js.map +1 -0
  218. package/lib/operations/search_indexes/update.js +35 -0
  219. package/lib/operations/search_indexes/update.js.map +1 -0
  220. package/lib/operations/set_profiling_level.js +53 -0
  221. package/lib/operations/set_profiling_level.js.map +1 -0
  222. package/lib/operations/stats.js +27 -0
  223. package/lib/operations/stats.js.map +1 -0
  224. package/lib/operations/update.js +188 -0
  225. package/lib/operations/update.js.map +1 -0
  226. package/lib/operations/validate_collection.js +37 -0
  227. package/lib/operations/validate_collection.js.map +1 -0
  228. package/lib/read_concern.js +73 -0
  229. package/lib/read_concern.js.map +1 -0
  230. package/lib/read_preference.js +191 -0
  231. package/lib/read_preference.js.map +1 -0
  232. package/lib/sdam/common.js +49 -0
  233. package/lib/sdam/common.js.map +1 -0
  234. package/lib/sdam/events.js +146 -0
  235. package/lib/sdam/events.js.map +1 -0
  236. package/lib/sdam/monitor.js +544 -0
  237. package/lib/sdam/monitor.js.map +1 -0
  238. package/lib/sdam/server.js +404 -0
  239. package/lib/sdam/server.js.map +1 -0
  240. package/lib/sdam/server_description.js +204 -0
  241. package/lib/sdam/server_description.js.map +1 -0
  242. package/lib/sdam/server_selection.js +294 -0
  243. package/lib/sdam/server_selection.js.map +1 -0
  244. package/lib/sdam/server_selection_events.js +85 -0
  245. package/lib/sdam/server_selection_events.js.map +1 -0
  246. package/lib/sdam/srv_polling.js +108 -0
  247. package/lib/sdam/srv_polling.js.map +1 -0
  248. package/lib/sdam/topology.js +652 -0
  249. package/lib/sdam/topology.js.map +1 -0
  250. package/lib/sdam/topology_description.js +383 -0
  251. package/lib/sdam/topology_description.js.map +1 -0
  252. package/lib/sessions.js +892 -0
  253. package/lib/sessions.js.map +1 -0
  254. package/lib/sort.js +103 -0
  255. package/lib/sort.js.map +1 -0
  256. package/lib/timeout.js +296 -0
  257. package/lib/timeout.js.map +1 -0
  258. package/lib/transactions.js +135 -0
  259. package/lib/transactions.js.map +1 -0
  260. package/lib/utils.js +1163 -0
  261. package/lib/utils.js.map +1 -0
  262. package/lib/write_concern.js +100 -0
  263. package/lib/write_concern.js.map +1 -0
  264. package/mongodb.d.ts +9018 -0
  265. package/package.json +197 -0
  266. package/src/admin.ts +173 -0
  267. package/src/bson.ts +149 -0
  268. package/src/bulk/common.ts +1251 -0
  269. package/src/bulk/ordered.ts +83 -0
  270. package/src/bulk/unordered.ts +115 -0
  271. package/src/change_stream.ts +1160 -0
  272. package/src/client-side-encryption/auto_encrypter.ts +469 -0
  273. package/src/client-side-encryption/client_encryption.ts +1150 -0
  274. package/src/client-side-encryption/errors.ts +144 -0
  275. package/src/client-side-encryption/mongocryptd_manager.ts +100 -0
  276. package/src/client-side-encryption/providers/aws.ts +33 -0
  277. package/src/client-side-encryption/providers/azure.ts +181 -0
  278. package/src/client-side-encryption/providers/gcp.ts +16 -0
  279. package/src/client-side-encryption/providers/index.ts +207 -0
  280. package/src/client-side-encryption/state_machine.ts +651 -0
  281. package/src/cmap/auth/auth_provider.ts +77 -0
  282. package/src/cmap/auth/aws4.ts +207 -0
  283. package/src/cmap/auth/aws_temporary_credentials.ts +129 -0
  284. package/src/cmap/auth/gssapi.ts +203 -0
  285. package/src/cmap/auth/mongo_credentials.ts +292 -0
  286. package/src/cmap/auth/mongodb_aws.ts +179 -0
  287. package/src/cmap/auth/mongodb_oidc/automated_callback_workflow.ts +88 -0
  288. package/src/cmap/auth/mongodb_oidc/azure_machine_workflow.ts +73 -0
  289. package/src/cmap/auth/mongodb_oidc/callback_workflow.ts +188 -0
  290. package/src/cmap/auth/mongodb_oidc/command_builders.ts +53 -0
  291. package/src/cmap/auth/mongodb_oidc/gcp_machine_workflow.ts +46 -0
  292. package/src/cmap/auth/mongodb_oidc/human_callback_workflow.ts +141 -0
  293. package/src/cmap/auth/mongodb_oidc/k8s_machine_workflow.ts +31 -0
  294. package/src/cmap/auth/mongodb_oidc/token_cache.ts +62 -0
  295. package/src/cmap/auth/mongodb_oidc/token_machine_workflow.ts +22 -0
  296. package/src/cmap/auth/mongodb_oidc.ts +185 -0
  297. package/src/cmap/auth/plain.ts +25 -0
  298. package/src/cmap/auth/providers.ts +22 -0
  299. package/src/cmap/auth/scram.ts +344 -0
  300. package/src/cmap/auth/x509.ts +43 -0
  301. package/src/cmap/command_monitoring_events.ts +316 -0
  302. package/src/cmap/commands.ts +788 -0
  303. package/src/cmap/connect.ts +518 -0
  304. package/src/cmap/connection.ts +931 -0
  305. package/src/cmap/connection_pool.ts +831 -0
  306. package/src/cmap/connection_pool_events.ts +300 -0
  307. package/src/cmap/errors.ts +119 -0
  308. package/src/cmap/handshake/client_metadata.ts +353 -0
  309. package/src/cmap/metrics.ts +58 -0
  310. package/src/cmap/stream_description.ts +96 -0
  311. package/src/cmap/wire_protocol/compression.ts +211 -0
  312. package/src/cmap/wire_protocol/constants.ts +17 -0
  313. package/src/cmap/wire_protocol/on_data.ts +139 -0
  314. package/src/cmap/wire_protocol/on_demand/document.ts +358 -0
  315. package/src/cmap/wire_protocol/responses.ts +393 -0
  316. package/src/cmap/wire_protocol/shared.ts +48 -0
  317. package/src/collection.ts +1314 -0
  318. package/src/connection_string.ts +1297 -0
  319. package/src/constants.ts +176 -0
  320. package/src/cursor/abstract_cursor.ts +1247 -0
  321. package/src/cursor/aggregation_cursor.ts +245 -0
  322. package/src/cursor/change_stream_cursor.ts +171 -0
  323. package/src/cursor/client_bulk_write_cursor.ts +83 -0
  324. package/src/cursor/explainable_cursor.ts +51 -0
  325. package/src/cursor/find_cursor.ts +497 -0
  326. package/src/cursor/list_collections_cursor.ts +50 -0
  327. package/src/cursor/list_indexes_cursor.ts +37 -0
  328. package/src/cursor/list_search_indexes_cursor.ts +20 -0
  329. package/src/cursor/run_command_cursor.ts +178 -0
  330. package/src/db.ts +621 -0
  331. package/src/deps.ts +227 -0
  332. package/src/encrypter.ts +127 -0
  333. package/src/error.ts +1567 -0
  334. package/src/explain.ts +124 -0
  335. package/src/gridfs/download.ts +483 -0
  336. package/src/gridfs/index.ts +264 -0
  337. package/src/gridfs/upload.ts +537 -0
  338. package/src/index.ts +633 -0
  339. package/src/mongo_client.ts +1155 -0
  340. package/src/mongo_client_auth_providers.ts +87 -0
  341. package/src/mongo_logger.ts +1081 -0
  342. package/src/mongo_types.ts +678 -0
  343. package/src/operations/aggregate.ts +153 -0
  344. package/src/operations/client_bulk_write/client_bulk_write.ts +72 -0
  345. package/src/operations/client_bulk_write/command_builder.ts +487 -0
  346. package/src/operations/client_bulk_write/common.ts +276 -0
  347. package/src/operations/client_bulk_write/executor.ts +149 -0
  348. package/src/operations/client_bulk_write/results_merger.ts +260 -0
  349. package/src/operations/command.ts +171 -0
  350. package/src/operations/count.ts +74 -0
  351. package/src/operations/create_collection.ts +218 -0
  352. package/src/operations/delete.ts +183 -0
  353. package/src/operations/distinct.ts +92 -0
  354. package/src/operations/drop.ts +130 -0
  355. package/src/operations/end_sessions.ts +44 -0
  356. package/src/operations/estimated_document_count.ts +61 -0
  357. package/src/operations/execute_operation.ts +319 -0
  358. package/src/operations/find.ts +254 -0
  359. package/src/operations/find_and_modify.ts +319 -0
  360. package/src/operations/get_more.ts +108 -0
  361. package/src/operations/indexes.ts +418 -0
  362. package/src/operations/insert.ts +108 -0
  363. package/src/operations/kill_cursors.ts +64 -0
  364. package/src/operations/list_collections.ts +108 -0
  365. package/src/operations/list_databases.ts +68 -0
  366. package/src/operations/operation.ts +181 -0
  367. package/src/operations/profiling_level.ts +46 -0
  368. package/src/operations/remove_user.ts +36 -0
  369. package/src/operations/rename.ts +60 -0
  370. package/src/operations/run_command.ts +79 -0
  371. package/src/operations/search_indexes/create.ts +56 -0
  372. package/src/operations/search_indexes/drop.ts +58 -0
  373. package/src/operations/search_indexes/update.ts +45 -0
  374. package/src/operations/set_profiling_level.ts +74 -0
  375. package/src/operations/stats.ts +37 -0
  376. package/src/operations/update.ts +318 -0
  377. package/src/operations/validate_collection.ts +50 -0
  378. package/src/read_concern.ts +88 -0
  379. package/src/read_preference.ts +256 -0
  380. package/src/sdam/common.ts +74 -0
  381. package/src/sdam/events.ts +219 -0
  382. package/src/sdam/monitor.ts +771 -0
  383. package/src/sdam/server.ts +595 -0
  384. package/src/sdam/server_description.ts +297 -0
  385. package/src/sdam/server_selection.ts +415 -0
  386. package/src/sdam/server_selection_events.ts +142 -0
  387. package/src/sdam/srv_polling.ts +146 -0
  388. package/src/sdam/topology.ts +1100 -0
  389. package/src/sdam/topology_description.ts +548 -0
  390. package/src/sessions.ts +1244 -0
  391. package/src/sort.ts +141 -0
  392. package/src/timeout.ts +405 -0
  393. package/src/transactions.ts +181 -0
  394. package/src/utils.ts +1434 -0
  395. package/src/write_concern.ts +183 -0
  396. package/tsconfig.json +46 -0
@@ -0,0 +1,1251 @@
1
+ import { type BSONSerializeOptions, type Document, EJSON, resolveBSONOptions } from '../bson';
2
+ import type { Collection } from '../collection';
3
+ import {
4
+ type AnyError,
5
+ MongoBatchReExecutionError,
6
+ MONGODB_ERROR_CODES,
7
+ MongoInvalidArgumentError,
8
+ MongoRuntimeError,
9
+ MongoServerError,
10
+ MongoWriteConcernError
11
+ } from '../error';
12
+ import type { Filter, OneOrMore, OptionalId, UpdateFilter, WithoutId } from '../mongo_types';
13
+ import type { CollationOptions, CommandOperationOptions } from '../operations/command';
14
+ import { DeleteOperation, type DeleteStatement, makeDeleteStatement } from '../operations/delete';
15
+ import { executeOperation } from '../operations/execute_operation';
16
+ import { InsertOperation } from '../operations/insert';
17
+ import { type Hint } from '../operations/operation';
18
+ import { makeUpdateStatement, UpdateOperation, type UpdateStatement } from '../operations/update';
19
+ import type { Topology } from '../sdam/topology';
20
+ import { type Sort } from '../sort';
21
+ import { TimeoutContext } from '../timeout';
22
+ import {
23
+ getTopology,
24
+ hasAtomicOperators,
25
+ maybeAddIdToDocuments,
26
+ type MongoDBNamespace,
27
+ resolveOptions
28
+ } from '../utils';
29
+ import { WriteConcern } from '../write_concern';
30
+
31
+ /** @public */
32
+ export const BatchType = Object.freeze({
33
+ INSERT: 1,
34
+ UPDATE: 2,
35
+ DELETE: 3
36
+ } as const);
37
+
38
+ /** @public */
39
+ export type BatchType = (typeof BatchType)[keyof typeof BatchType];
40
+
41
+ /** @public */
42
+ export interface InsertOneModel<TSchema extends Document = Document> {
43
+ /** The document to insert. */
44
+ document: OptionalId<TSchema>;
45
+ }
46
+
47
+ /** @public */
48
+ export interface DeleteOneModel<TSchema extends Document = Document> {
49
+ /** The filter to limit the deleted documents. */
50
+ filter: Filter<TSchema>;
51
+ /** Specifies a collation. */
52
+ collation?: CollationOptions;
53
+ /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
54
+ hint?: Hint;
55
+ }
56
+
57
+ /** @public */
58
+ export interface DeleteManyModel<TSchema extends Document = Document> {
59
+ /** The filter to limit the deleted documents. */
60
+ filter: Filter<TSchema>;
61
+ /** Specifies a collation. */
62
+ collation?: CollationOptions;
63
+ /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
64
+ hint?: Hint;
65
+ }
66
+
67
+ /** @public */
68
+ export interface ReplaceOneModel<TSchema extends Document = Document> {
69
+ /** The filter that specifies which document to replace. In the case of multiple matches, the first document matched is replaced. */
70
+ filter: Filter<TSchema>;
71
+ /** The document with which to replace the matched document. */
72
+ replacement: WithoutId<TSchema>;
73
+ /** Specifies a collation. */
74
+ collation?: CollationOptions;
75
+ /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
76
+ hint?: Hint;
77
+ /** When true, creates a new document if no document matches the query. */
78
+ upsert?: boolean;
79
+ /** Specifies the sort order for the documents matched by the filter. */
80
+ sort?: Sort;
81
+ }
82
+
83
+ /** @public */
84
+ export interface UpdateOneModel<TSchema extends Document = Document> {
85
+ /** The filter that specifies which document to update. In the case of multiple matches, the first document matched is updated. */
86
+ filter: Filter<TSchema>;
87
+ /**
88
+ * The modifications to apply. The value can be either:
89
+ * UpdateFilter<TSchema> - A document that contains update operator expressions,
90
+ * Document[] - an aggregation pipeline.
91
+ */
92
+ update: UpdateFilter<TSchema> | Document[];
93
+ /** A set of filters specifying to which array elements an update should apply. */
94
+ arrayFilters?: Document[];
95
+ /** Specifies a collation. */
96
+ collation?: CollationOptions;
97
+ /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
98
+ hint?: Hint;
99
+ /** When true, creates a new document if no document matches the query. */
100
+ upsert?: boolean;
101
+ /** Specifies the sort order for the documents matched by the filter. */
102
+ sort?: Sort;
103
+ }
104
+
105
+ /** @public */
106
+ export interface UpdateManyModel<TSchema extends Document = Document> {
107
+ /** The filter to limit the updated documents. */
108
+ filter: Filter<TSchema>;
109
+ /**
110
+ * The modifications to apply. The value can be either:
111
+ * UpdateFilter<TSchema> - A document that contains update operator expressions,
112
+ * Document[] - an aggregation pipeline.
113
+ */
114
+ update: UpdateFilter<TSchema> | Document[];
115
+ /** A set of filters specifying to which array elements an update should apply. */
116
+ arrayFilters?: Document[];
117
+ /** Specifies a collation. */
118
+ collation?: CollationOptions;
119
+ /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
120
+ hint?: Hint;
121
+ /** When true, creates a new document if no document matches the query. */
122
+ upsert?: boolean;
123
+ }
124
+
125
+ /** @public */
126
+ export type AnyBulkWriteOperation<TSchema extends Document = Document> =
127
+ | { insertOne: InsertOneModel<TSchema> }
128
+ | { replaceOne: ReplaceOneModel<TSchema> }
129
+ | { updateOne: UpdateOneModel<TSchema> }
130
+ | { updateMany: UpdateManyModel<TSchema> }
131
+ | { deleteOne: DeleteOneModel<TSchema> }
132
+ | { deleteMany: DeleteManyModel<TSchema> };
133
+
134
+ /** @internal */
135
+ export interface BulkResult {
136
+ ok: number;
137
+ writeErrors: WriteError[];
138
+ writeConcernErrors: WriteConcernError[];
139
+ insertedIds: Document[];
140
+ nInserted: number;
141
+ nUpserted: number;
142
+ nMatched: number;
143
+ nModified: number;
144
+ nRemoved: number;
145
+ upserted: Document[];
146
+ }
147
+
148
+ /**
149
+ * Keeps the state of a unordered batch so we can rewrite the results
150
+ * correctly after command execution
151
+ *
152
+ * @public
153
+ */
154
+ export class Batch<T = Document> {
155
+ originalZeroIndex: number;
156
+ currentIndex: number;
157
+ originalIndexes: number[];
158
+ batchType: BatchType;
159
+ operations: T[];
160
+ size: number;
161
+ sizeBytes: number;
162
+
163
+ constructor(batchType: BatchType, originalZeroIndex: number) {
164
+ this.originalZeroIndex = originalZeroIndex;
165
+ this.currentIndex = 0;
166
+ this.originalIndexes = [];
167
+ this.batchType = batchType;
168
+ this.operations = [];
169
+ this.size = 0;
170
+ this.sizeBytes = 0;
171
+ }
172
+ }
173
+
174
+ /**
175
+ * @public
176
+ * The result of a bulk write.
177
+ */
178
+ export class BulkWriteResult {
179
+ private readonly result: BulkResult;
180
+ /** Number of documents inserted. */
181
+ readonly insertedCount: number;
182
+ /** Number of documents matched for update. */
183
+ readonly matchedCount: number;
184
+ /** Number of documents modified. */
185
+ readonly modifiedCount: number;
186
+ /** Number of documents deleted. */
187
+ readonly deletedCount: number;
188
+ /** Number of documents upserted. */
189
+ readonly upsertedCount: number;
190
+ /** Upserted document generated Id's, hash key is the index of the originating operation */
191
+ readonly upsertedIds: { [key: number]: any };
192
+ /** Inserted document generated Id's, hash key is the index of the originating operation */
193
+ readonly insertedIds: { [key: number]: any };
194
+
195
+ private static generateIdMap(ids: Document[]): { [key: number]: any } {
196
+ const idMap: { [index: number]: any } = {};
197
+ for (const doc of ids) {
198
+ idMap[doc.index] = doc._id;
199
+ }
200
+ return idMap;
201
+ }
202
+
203
+ /**
204
+ * Create a new BulkWriteResult instance
205
+ * @internal
206
+ */
207
+ constructor(bulkResult: BulkResult, isOrdered: boolean) {
208
+ this.result = bulkResult;
209
+ this.insertedCount = this.result.nInserted ?? 0;
210
+ this.matchedCount = this.result.nMatched ?? 0;
211
+ this.modifiedCount = this.result.nModified ?? 0;
212
+ this.deletedCount = this.result.nRemoved ?? 0;
213
+ this.upsertedCount = this.result.upserted.length ?? 0;
214
+ this.upsertedIds = BulkWriteResult.generateIdMap(this.result.upserted);
215
+ this.insertedIds = BulkWriteResult.generateIdMap(
216
+ this.getSuccessfullyInsertedIds(bulkResult, isOrdered)
217
+ );
218
+ Object.defineProperty(this, 'result', { value: this.result, enumerable: false });
219
+ }
220
+
221
+ /** Evaluates to true if the bulk operation correctly executes */
222
+ get ok(): number {
223
+ return this.result.ok;
224
+ }
225
+
226
+ /**
227
+ * Returns document_ids that were actually inserted
228
+ * @internal
229
+ */
230
+ private getSuccessfullyInsertedIds(bulkResult: BulkResult, isOrdered: boolean): Document[] {
231
+ if (bulkResult.writeErrors.length === 0) return bulkResult.insertedIds;
232
+
233
+ if (isOrdered) {
234
+ return bulkResult.insertedIds.slice(0, bulkResult.writeErrors[0].index);
235
+ }
236
+
237
+ return bulkResult.insertedIds.filter(
238
+ ({ index }) => !bulkResult.writeErrors.some(writeError => index === writeError.index)
239
+ );
240
+ }
241
+
242
+ /** Returns the upserted id at the given index */
243
+ getUpsertedIdAt(index: number): Document | undefined {
244
+ return this.result.upserted[index];
245
+ }
246
+
247
+ /** Returns raw internal result */
248
+ getRawResponse(): Document {
249
+ return this.result;
250
+ }
251
+
252
+ /** Returns true if the bulk operation contains a write error */
253
+ hasWriteErrors(): boolean {
254
+ return this.result.writeErrors.length > 0;
255
+ }
256
+
257
+ /** Returns the number of write errors from the bulk operation */
258
+ getWriteErrorCount(): number {
259
+ return this.result.writeErrors.length;
260
+ }
261
+
262
+ /** Returns a specific write error object */
263
+ getWriteErrorAt(index: number): WriteError | undefined {
264
+ return index < this.result.writeErrors.length ? this.result.writeErrors[index] : undefined;
265
+ }
266
+
267
+ /** Retrieve all write errors */
268
+ getWriteErrors(): WriteError[] {
269
+ return this.result.writeErrors;
270
+ }
271
+
272
+ /** Retrieve the write concern error if one exists */
273
+ getWriteConcernError(): WriteConcernError | undefined {
274
+ if (this.result.writeConcernErrors.length === 0) {
275
+ return;
276
+ } else if (this.result.writeConcernErrors.length === 1) {
277
+ // Return the error
278
+ return this.result.writeConcernErrors[0];
279
+ } else {
280
+ // Combine the errors
281
+ let errmsg = '';
282
+ for (let i = 0; i < this.result.writeConcernErrors.length; i++) {
283
+ const err = this.result.writeConcernErrors[i];
284
+ errmsg = errmsg + err.errmsg;
285
+
286
+ // TODO: Something better
287
+ if (i === 0) errmsg = errmsg + ' and ';
288
+ }
289
+
290
+ return new WriteConcernError({ errmsg, code: MONGODB_ERROR_CODES.WriteConcernTimeout });
291
+ }
292
+ }
293
+
294
+ toString(): string {
295
+ return `BulkWriteResult(${EJSON.stringify(this.result)})`;
296
+ }
297
+
298
+ isOk(): boolean {
299
+ return this.result.ok === 1;
300
+ }
301
+ }
302
+
303
+ /** @public */
304
+ export interface WriteConcernErrorData {
305
+ code: number;
306
+ errmsg: string;
307
+ errInfo?: Document;
308
+ }
309
+
310
+ /**
311
+ * An error representing a failure by the server to apply the requested write concern to the bulk operation.
312
+ * @public
313
+ * @category Error
314
+ */
315
+ export class WriteConcernError {
316
+ /** @internal */
317
+ private serverError: WriteConcernErrorData;
318
+
319
+ constructor(error: WriteConcernErrorData) {
320
+ this.serverError = error;
321
+ }
322
+
323
+ /** Write concern error code. */
324
+ get code(): number | undefined {
325
+ return this.serverError.code;
326
+ }
327
+
328
+ /** Write concern error message. */
329
+ get errmsg(): string | undefined {
330
+ return this.serverError.errmsg;
331
+ }
332
+
333
+ /** Write concern error info. */
334
+ get errInfo(): Document | undefined {
335
+ return this.serverError.errInfo;
336
+ }
337
+
338
+ toJSON(): WriteConcernErrorData {
339
+ return this.serverError;
340
+ }
341
+
342
+ toString(): string {
343
+ return `WriteConcernError(${this.errmsg})`;
344
+ }
345
+ }
346
+
347
+ /** @public */
348
+ export interface BulkWriteOperationError {
349
+ index: number;
350
+ code: number;
351
+ errmsg: string;
352
+ errInfo: Document;
353
+ op: Document | UpdateStatement | DeleteStatement;
354
+ }
355
+
356
+ /**
357
+ * An error that occurred during a BulkWrite on the server.
358
+ * @public
359
+ * @category Error
360
+ */
361
+ export class WriteError {
362
+ err: BulkWriteOperationError;
363
+
364
+ constructor(err: BulkWriteOperationError) {
365
+ this.err = err;
366
+ }
367
+
368
+ /** WriteError code. */
369
+ get code(): number {
370
+ return this.err.code;
371
+ }
372
+
373
+ /** WriteError original bulk operation index. */
374
+ get index(): number {
375
+ return this.err.index;
376
+ }
377
+
378
+ /** WriteError message. */
379
+ get errmsg(): string | undefined {
380
+ return this.err.errmsg;
381
+ }
382
+
383
+ /** WriteError details. */
384
+ get errInfo(): Document | undefined {
385
+ return this.err.errInfo;
386
+ }
387
+
388
+ /** Returns the underlying operation that caused the error */
389
+ getOperation(): Document {
390
+ return this.err.op;
391
+ }
392
+
393
+ toJSON(): { code: number; index: number; errmsg?: string; op: Document } {
394
+ return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op };
395
+ }
396
+
397
+ toString(): string {
398
+ return `WriteError(${JSON.stringify(this.toJSON())})`;
399
+ }
400
+ }
401
+
402
+ /** Merges results into shared data structure */
403
+ export function mergeBatchResults(
404
+ batch: Batch,
405
+ bulkResult: BulkResult,
406
+ err?: AnyError,
407
+ result?: Document
408
+ ): void {
409
+ // If we have an error set the result to be the err object
410
+ if (err) {
411
+ result = err;
412
+ } else if (result && result.result) {
413
+ result = result.result;
414
+ }
415
+
416
+ if (result == null) {
417
+ return;
418
+ }
419
+
420
+ // Do we have a top level error stop processing and return
421
+ if (result.ok === 0 && bulkResult.ok === 1) {
422
+ bulkResult.ok = 0;
423
+
424
+ const writeError = {
425
+ index: 0,
426
+ code: result.code || 0,
427
+ errmsg: result.message,
428
+ errInfo: result.errInfo,
429
+ op: batch.operations[0]
430
+ };
431
+
432
+ bulkResult.writeErrors.push(new WriteError(writeError));
433
+ return;
434
+ } else if (result.ok === 0 && bulkResult.ok === 0) {
435
+ return;
436
+ }
437
+
438
+ // If we have an insert Batch type
439
+ if (isInsertBatch(batch) && result.n) {
440
+ bulkResult.nInserted = bulkResult.nInserted + result.n;
441
+ }
442
+
443
+ // If we have an insert Batch type
444
+ if (isDeleteBatch(batch) && result.n) {
445
+ bulkResult.nRemoved = bulkResult.nRemoved + result.n;
446
+ }
447
+
448
+ let nUpserted = 0;
449
+
450
+ // We have an array of upserted values, we need to rewrite the indexes
451
+ if (Array.isArray(result.upserted)) {
452
+ nUpserted = result.upserted.length;
453
+
454
+ for (let i = 0; i < result.upserted.length; i++) {
455
+ bulkResult.upserted.push({
456
+ index: result.upserted[i].index + batch.originalZeroIndex,
457
+ _id: result.upserted[i]._id
458
+ });
459
+ }
460
+ } else if (result.upserted) {
461
+ nUpserted = 1;
462
+
463
+ bulkResult.upserted.push({
464
+ index: batch.originalZeroIndex,
465
+ _id: result.upserted
466
+ });
467
+ }
468
+
469
+ // If we have an update Batch type
470
+ if (isUpdateBatch(batch) && result.n) {
471
+ const nModified = result.nModified;
472
+ bulkResult.nUpserted = bulkResult.nUpserted + nUpserted;
473
+ bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted);
474
+
475
+ if (typeof nModified === 'number') {
476
+ bulkResult.nModified = bulkResult.nModified + nModified;
477
+ } else {
478
+ bulkResult.nModified = 0;
479
+ }
480
+ }
481
+
482
+ if (Array.isArray(result.writeErrors)) {
483
+ for (let i = 0; i < result.writeErrors.length; i++) {
484
+ const writeError = {
485
+ index: batch.originalIndexes[result.writeErrors[i].index],
486
+ code: result.writeErrors[i].code,
487
+ errmsg: result.writeErrors[i].errmsg,
488
+ errInfo: result.writeErrors[i].errInfo,
489
+ op: batch.operations[result.writeErrors[i].index]
490
+ };
491
+
492
+ bulkResult.writeErrors.push(new WriteError(writeError));
493
+ }
494
+ }
495
+
496
+ if (result.writeConcernError) {
497
+ bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError));
498
+ }
499
+ }
500
+
501
+ async function executeCommands(
502
+ bulkOperation: BulkOperationBase,
503
+ options: BulkWriteOptions & { timeoutContext?: TimeoutContext | null }
504
+ ): Promise<BulkWriteResult> {
505
+ if (bulkOperation.s.batches.length === 0) {
506
+ return new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered);
507
+ }
508
+
509
+ for (const batch of bulkOperation.s.batches) {
510
+ const finalOptions = resolveOptions(bulkOperation, {
511
+ ...options,
512
+ ordered: bulkOperation.isOrdered
513
+ });
514
+
515
+ if (finalOptions.bypassDocumentValidation !== true) {
516
+ delete finalOptions.bypassDocumentValidation;
517
+ }
518
+
519
+ // Is the bypassDocumentValidation options specific
520
+ if (bulkOperation.s.bypassDocumentValidation === true) {
521
+ finalOptions.bypassDocumentValidation = true;
522
+ }
523
+
524
+ // Is the checkKeys option disabled
525
+ if (bulkOperation.s.checkKeys === false) {
526
+ finalOptions.checkKeys = false;
527
+ }
528
+
529
+ if (bulkOperation.retryWrites) {
530
+ if (isUpdateBatch(batch)) {
531
+ bulkOperation.retryWrites =
532
+ bulkOperation.retryWrites && !batch.operations.some(op => op.multi);
533
+ }
534
+
535
+ if (isDeleteBatch(batch)) {
536
+ bulkOperation.retryWrites =
537
+ bulkOperation.retryWrites && !batch.operations.some(op => op.limit === 0);
538
+ }
539
+ }
540
+
541
+ const operation = isInsertBatch(batch)
542
+ ? new InsertOperation(bulkOperation.s.namespace, batch.operations, finalOptions)
543
+ : isUpdateBatch(batch)
544
+ ? new UpdateOperation(bulkOperation.s.namespace, batch.operations, finalOptions)
545
+ : isDeleteBatch(batch)
546
+ ? new DeleteOperation(bulkOperation.s.namespace, batch.operations, finalOptions)
547
+ : null;
548
+
549
+ if (operation == null) throw new MongoRuntimeError(`Unknown batchType: ${batch.batchType}`);
550
+
551
+ let thrownError = null;
552
+ let result;
553
+ try {
554
+ result = await executeOperation(
555
+ bulkOperation.s.collection.client,
556
+ operation,
557
+ finalOptions.timeoutContext
558
+ );
559
+ } catch (error) {
560
+ thrownError = error;
561
+ }
562
+
563
+ if (thrownError != null) {
564
+ if (thrownError instanceof MongoWriteConcernError) {
565
+ mergeBatchResults(batch, bulkOperation.s.bulkResult, thrownError, result);
566
+ const writeResult = new BulkWriteResult(
567
+ bulkOperation.s.bulkResult,
568
+ bulkOperation.isOrdered
569
+ );
570
+
571
+ throw new MongoBulkWriteError(
572
+ {
573
+ message: thrownError.result.writeConcernError.errmsg,
574
+ code: thrownError.result.writeConcernError.code
575
+ },
576
+ writeResult
577
+ );
578
+ } else {
579
+ // Error is a driver related error not a bulk op error, return early
580
+ throw new MongoBulkWriteError(
581
+ thrownError,
582
+ new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered)
583
+ );
584
+ }
585
+ }
586
+
587
+ mergeBatchResults(batch, bulkOperation.s.bulkResult, thrownError, result);
588
+ const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered);
589
+ bulkOperation.handleWriteError(writeResult);
590
+ }
591
+
592
+ bulkOperation.s.batches.length = 0;
593
+
594
+ const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult, bulkOperation.isOrdered);
595
+ bulkOperation.handleWriteError(writeResult);
596
+ return writeResult;
597
+ }
598
+
599
+ /**
600
+ * An error indicating an unsuccessful Bulk Write
601
+ * @public
602
+ * @category Error
603
+ */
604
+ export class MongoBulkWriteError extends MongoServerError {
605
+ result: BulkWriteResult;
606
+ writeErrors: OneOrMore<WriteError> = [];
607
+ err?: WriteConcernError;
608
+
609
+ /**
610
+ * **Do not use this constructor!**
611
+ *
612
+ * Meant for internal use only.
613
+ *
614
+ * @remarks
615
+ * This class is only meant to be constructed within the driver. This constructor is
616
+ * not subject to semantic versioning compatibility guarantees and may change at any time.
617
+ *
618
+ * @public
619
+ **/
620
+ constructor(
621
+ error:
622
+ | { message: string; code: number; writeErrors?: WriteError[] }
623
+ | WriteConcernError
624
+ | AnyError,
625
+ result: BulkWriteResult
626
+ ) {
627
+ super(error);
628
+
629
+ if (error instanceof WriteConcernError) this.err = error;
630
+ else if (!(error instanceof Error)) {
631
+ this.message = error.message;
632
+ this.code = error.code;
633
+ this.writeErrors = error.writeErrors ?? [];
634
+ }
635
+
636
+ this.result = result;
637
+ Object.assign(this, error);
638
+ }
639
+
640
+ override get name(): string {
641
+ return 'MongoBulkWriteError';
642
+ }
643
+
644
+ /** Number of documents inserted. */
645
+ get insertedCount(): number {
646
+ return this.result.insertedCount;
647
+ }
648
+ /** Number of documents matched for update. */
649
+ get matchedCount(): number {
650
+ return this.result.matchedCount;
651
+ }
652
+ /** Number of documents modified. */
653
+ get modifiedCount(): number {
654
+ return this.result.modifiedCount;
655
+ }
656
+ /** Number of documents deleted. */
657
+ get deletedCount(): number {
658
+ return this.result.deletedCount;
659
+ }
660
+ /** Number of documents upserted. */
661
+ get upsertedCount(): number {
662
+ return this.result.upsertedCount;
663
+ }
664
+ /** Inserted document generated Id's, hash key is the index of the originating operation */
665
+ get insertedIds(): { [key: number]: any } {
666
+ return this.result.insertedIds;
667
+ }
668
+ /** Upserted document generated Id's, hash key is the index of the originating operation */
669
+ get upsertedIds(): { [key: number]: any } {
670
+ return this.result.upsertedIds;
671
+ }
672
+ }
673
+
674
+ /**
675
+ * A builder object that is returned from {@link BulkOperationBase#find}.
676
+ * Is used to build a write operation that involves a query filter.
677
+ *
678
+ * @public
679
+ */
680
+ export class FindOperators {
681
+ bulkOperation: BulkOperationBase;
682
+
683
+ /**
684
+ * Creates a new FindOperators object.
685
+ * @internal
686
+ */
687
+ constructor(bulkOperation: BulkOperationBase) {
688
+ this.bulkOperation = bulkOperation;
689
+ }
690
+
691
+ /** Add a multiple update operation to the bulk operation */
692
+ update(updateDocument: Document | Document[]): BulkOperationBase {
693
+ const currentOp = buildCurrentOp(this.bulkOperation);
694
+ return this.bulkOperation.addToOperationsList(
695
+ BatchType.UPDATE,
696
+ makeUpdateStatement(currentOp.selector, updateDocument, {
697
+ ...currentOp,
698
+ multi: true
699
+ })
700
+ );
701
+ }
702
+
703
+ /** Add a single update operation to the bulk operation */
704
+ updateOne(updateDocument: Document | Document[]): BulkOperationBase {
705
+ if (!hasAtomicOperators(updateDocument, this.bulkOperation.bsonOptions)) {
706
+ throw new MongoInvalidArgumentError('Update document requires atomic operators');
707
+ }
708
+
709
+ const currentOp = buildCurrentOp(this.bulkOperation);
710
+ return this.bulkOperation.addToOperationsList(
711
+ BatchType.UPDATE,
712
+ makeUpdateStatement(currentOp.selector, updateDocument, { ...currentOp, multi: false })
713
+ );
714
+ }
715
+
716
+ /** Add a replace one operation to the bulk operation */
717
+ replaceOne(replacement: Document): BulkOperationBase {
718
+ if (hasAtomicOperators(replacement)) {
719
+ throw new MongoInvalidArgumentError('Replacement document must not use atomic operators');
720
+ }
721
+
722
+ const currentOp = buildCurrentOp(this.bulkOperation);
723
+ return this.bulkOperation.addToOperationsList(
724
+ BatchType.UPDATE,
725
+ makeUpdateStatement(currentOp.selector, replacement, { ...currentOp, multi: false })
726
+ );
727
+ }
728
+
729
+ /** Add a delete one operation to the bulk operation */
730
+ deleteOne(): BulkOperationBase {
731
+ const currentOp = buildCurrentOp(this.bulkOperation);
732
+ return this.bulkOperation.addToOperationsList(
733
+ BatchType.DELETE,
734
+ makeDeleteStatement(currentOp.selector, { ...currentOp, limit: 1 })
735
+ );
736
+ }
737
+
738
+ /** Add a delete many operation to the bulk operation */
739
+ delete(): BulkOperationBase {
740
+ const currentOp = buildCurrentOp(this.bulkOperation);
741
+ return this.bulkOperation.addToOperationsList(
742
+ BatchType.DELETE,
743
+ makeDeleteStatement(currentOp.selector, { ...currentOp, limit: 0 })
744
+ );
745
+ }
746
+
747
+ /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */
748
+ upsert(): this {
749
+ if (!this.bulkOperation.s.currentOp) {
750
+ this.bulkOperation.s.currentOp = {};
751
+ }
752
+
753
+ this.bulkOperation.s.currentOp.upsert = true;
754
+ return this;
755
+ }
756
+
757
+ /** Specifies the collation for the query condition. */
758
+ collation(collation: CollationOptions): this {
759
+ if (!this.bulkOperation.s.currentOp) {
760
+ this.bulkOperation.s.currentOp = {};
761
+ }
762
+
763
+ this.bulkOperation.s.currentOp.collation = collation;
764
+ return this;
765
+ }
766
+
767
+ /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */
768
+ arrayFilters(arrayFilters: Document[]): this {
769
+ if (!this.bulkOperation.s.currentOp) {
770
+ this.bulkOperation.s.currentOp = {};
771
+ }
772
+
773
+ this.bulkOperation.s.currentOp.arrayFilters = arrayFilters;
774
+ return this;
775
+ }
776
+
777
+ /** Specifies hint for the bulk operation. */
778
+ hint(hint: Hint): this {
779
+ if (!this.bulkOperation.s.currentOp) {
780
+ this.bulkOperation.s.currentOp = {};
781
+ }
782
+
783
+ this.bulkOperation.s.currentOp.hint = hint;
784
+ return this;
785
+ }
786
+ }
787
+
788
+ /** @internal */
789
+ export interface BulkOperationPrivate {
790
+ bulkResult: BulkResult;
791
+ currentBatch?: Batch;
792
+ currentIndex: number;
793
+ // ordered specific
794
+ currentBatchSize: number;
795
+ currentBatchSizeBytes: number;
796
+ // unordered specific
797
+ currentInsertBatch?: Batch;
798
+ currentUpdateBatch?: Batch;
799
+ currentRemoveBatch?: Batch;
800
+ batches: Batch[];
801
+ // Write concern
802
+ writeConcern?: WriteConcern;
803
+ // Max batch size options
804
+ maxBsonObjectSize: number;
805
+ maxBatchSizeBytes: number;
806
+ maxWriteBatchSize: number;
807
+ maxKeySize: number;
808
+ // Namespace
809
+ namespace: MongoDBNamespace;
810
+ // Topology
811
+ topology: Topology;
812
+ // Options
813
+ options: BulkWriteOptions;
814
+ // BSON options
815
+ bsonOptions: BSONSerializeOptions;
816
+ // Document used to build a bulk operation
817
+ currentOp?: Document;
818
+ // Executed
819
+ executed: boolean;
820
+ // Collection
821
+ collection: Collection;
822
+ // Fundamental error
823
+ err?: AnyError;
824
+ // check keys
825
+ checkKeys: boolean;
826
+ bypassDocumentValidation?: boolean;
827
+ }
828
+
829
+ /** @public */
830
+ export interface BulkWriteOptions extends CommandOperationOptions {
831
+ /**
832
+ * Allow driver to bypass schema validation.
833
+ * @defaultValue `false` - documents will be validated by default
834
+ **/
835
+ bypassDocumentValidation?: boolean;
836
+ /**
837
+ * If true, when an insert fails, don't execute the remaining writes.
838
+ * If false, continue with remaining inserts when one fails.
839
+ * @defaultValue `true` - inserts are ordered by default
840
+ */
841
+ ordered?: boolean;
842
+ /**
843
+ * Force server to assign _id values instead of driver.
844
+ * @defaultValue `false` - the driver generates `_id` fields by default
845
+ **/
846
+ forceServerObjectId?: boolean;
847
+ /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
848
+ let?: Document;
849
+
850
+ /** @internal */
851
+ timeoutContext?: TimeoutContext;
852
+ }
853
+
854
+ /** @public */
855
+ export abstract class BulkOperationBase {
856
+ isOrdered: boolean;
857
+ /** @internal */
858
+ s: BulkOperationPrivate;
859
+ operationId?: number;
860
+ private collection: Collection;
861
+ /** @internal */
862
+ retryWrites?: boolean;
863
+
864
+ /**
865
+ * Create a new OrderedBulkOperation or UnorderedBulkOperation instance
866
+ * @internal
867
+ */
868
+ constructor(collection: Collection, options: BulkWriteOptions, isOrdered: boolean) {
869
+ this.collection = collection;
870
+ this.retryWrites = collection.db.options?.retryWrites;
871
+ // determine whether bulkOperation is ordered or unordered
872
+ this.isOrdered = isOrdered;
873
+
874
+ const topology = getTopology(collection);
875
+ options = options == null ? {} : options;
876
+ // TODO Bring from driver information in hello
877
+ // Get the namespace for the write operations
878
+ const namespace = collection.s.namespace;
879
+ // Used to mark operation as executed
880
+ const executed = false;
881
+
882
+ // Current item
883
+ const currentOp = undefined;
884
+
885
+ // Set max byte size
886
+ const hello = topology.lastHello();
887
+
888
+ // If we have autoEncryption on, batch-splitting must be done on 2mb chunks, but single documents
889
+ // over 2mb are still allowed
890
+ const usingAutoEncryption = !!(topology.s.options && topology.s.options.autoEncrypter);
891
+ const maxBsonObjectSize =
892
+ hello && hello.maxBsonObjectSize ? hello.maxBsonObjectSize : 1024 * 1024 * 16;
893
+ const maxBatchSizeBytes = usingAutoEncryption ? 1024 * 1024 * 2 : maxBsonObjectSize;
894
+ const maxWriteBatchSize = hello && hello.maxWriteBatchSize ? hello.maxWriteBatchSize : 1000;
895
+
896
+ // Calculates the largest possible size of an Array key, represented as a BSON string
897
+ // element. This calculation:
898
+ // 1 byte for BSON type
899
+ // # of bytes = length of (string representation of (maxWriteBatchSize - 1))
900
+ // + 1 bytes for null terminator
901
+ const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2;
902
+
903
+ // Final results
904
+ const bulkResult: BulkResult = {
905
+ ok: 1,
906
+ writeErrors: [],
907
+ writeConcernErrors: [],
908
+ insertedIds: [],
909
+ nInserted: 0,
910
+ nUpserted: 0,
911
+ nMatched: 0,
912
+ nModified: 0,
913
+ nRemoved: 0,
914
+ upserted: []
915
+ };
916
+
917
+ // Internal state
918
+ this.s = {
919
+ // Final result
920
+ bulkResult,
921
+ // Current batch state
922
+ currentBatch: undefined,
923
+ currentIndex: 0,
924
+ // ordered specific
925
+ currentBatchSize: 0,
926
+ currentBatchSizeBytes: 0,
927
+ // unordered specific
928
+ currentInsertBatch: undefined,
929
+ currentUpdateBatch: undefined,
930
+ currentRemoveBatch: undefined,
931
+ batches: [],
932
+ // Write concern
933
+ writeConcern: WriteConcern.fromOptions(options),
934
+ // Max batch size options
935
+ maxBsonObjectSize,
936
+ maxBatchSizeBytes,
937
+ maxWriteBatchSize,
938
+ maxKeySize,
939
+ // Namespace
940
+ namespace,
941
+ // Topology
942
+ topology,
943
+ // Options
944
+ options: options,
945
+ // BSON options
946
+ bsonOptions: resolveBSONOptions(options),
947
+ // Current operation
948
+ currentOp,
949
+ // Executed
950
+ executed,
951
+ // Collection
952
+ collection,
953
+ // Fundamental error
954
+ err: undefined,
955
+ // check keys
956
+ checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : false
957
+ };
958
+
959
+ // bypass Validation
960
+ if (options.bypassDocumentValidation === true) {
961
+ this.s.bypassDocumentValidation = true;
962
+ }
963
+ }
964
+
965
+ /**
966
+ * Add a single insert document to the bulk operation
967
+ *
968
+ * @example
969
+ * ```ts
970
+ * const bulkOp = collection.initializeOrderedBulkOp();
971
+ *
972
+ * // Adds three inserts to the bulkOp.
973
+ * bulkOp
974
+ * .insert({ a: 1 })
975
+ * .insert({ b: 2 })
976
+ * .insert({ c: 3 });
977
+ * await bulkOp.execute();
978
+ * ```
979
+ */
980
+ insert(document: Document): BulkOperationBase {
981
+ maybeAddIdToDocuments(this.collection, document, {
982
+ forceServerObjectId: this.shouldForceServerObjectId()
983
+ });
984
+
985
+ return this.addToOperationsList(BatchType.INSERT, document);
986
+ }
987
+
988
+ /**
989
+ * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne.
990
+ * Returns a builder object used to complete the definition of the operation.
991
+ *
992
+ * @example
993
+ * ```ts
994
+ * const bulkOp = collection.initializeOrderedBulkOp();
995
+ *
996
+ * // Add an updateOne to the bulkOp
997
+ * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
998
+ *
999
+ * // Add an updateMany to the bulkOp
1000
+ * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
1001
+ *
1002
+ * // Add an upsert
1003
+ * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
1004
+ *
1005
+ * // Add a deletion
1006
+ * bulkOp.find({ g: 7 }).deleteOne();
1007
+ *
1008
+ * // Add a multi deletion
1009
+ * bulkOp.find({ h: 8 }).delete();
1010
+ *
1011
+ * // Add a replaceOne
1012
+ * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }});
1013
+ *
1014
+ * // Update using a pipeline (requires Mongodb 4.2 or higher)
1015
+ * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
1016
+ * { $set: { total: { $sum: [ '$y', '$z' ] } } }
1017
+ * ]);
1018
+ *
1019
+ * // All of the ops will now be executed
1020
+ * await bulkOp.execute();
1021
+ * ```
1022
+ */
1023
+ find(selector: Document): FindOperators {
1024
+ if (!selector) {
1025
+ throw new MongoInvalidArgumentError('Bulk find operation must specify a selector');
1026
+ }
1027
+
1028
+ // Save a current selector
1029
+ this.s.currentOp = {
1030
+ selector: selector
1031
+ };
1032
+
1033
+ return new FindOperators(this);
1034
+ }
1035
+
1036
+ /** Specifies a raw operation to perform in the bulk write. */
1037
+ raw(op: AnyBulkWriteOperation): this {
1038
+ if (op == null || typeof op !== 'object') {
1039
+ throw new MongoInvalidArgumentError('Operation must be an object with an operation key');
1040
+ }
1041
+ if ('insertOne' in op) {
1042
+ const forceServerObjectId = this.shouldForceServerObjectId();
1043
+ const document =
1044
+ op.insertOne && op.insertOne.document == null
1045
+ ? // TODO(NODE-6003): remove support for omitting the `documents` subdocument in bulk inserts
1046
+ (op.insertOne as Document)
1047
+ : op.insertOne.document;
1048
+
1049
+ maybeAddIdToDocuments(this.collection, document, { forceServerObjectId });
1050
+
1051
+ return this.addToOperationsList(BatchType.INSERT, document);
1052
+ }
1053
+
1054
+ if ('replaceOne' in op || 'updateOne' in op || 'updateMany' in op) {
1055
+ if ('replaceOne' in op) {
1056
+ if ('q' in op.replaceOne) {
1057
+ throw new MongoInvalidArgumentError('Raw operations are not allowed');
1058
+ }
1059
+ const updateStatement = makeUpdateStatement(
1060
+ op.replaceOne.filter,
1061
+ op.replaceOne.replacement,
1062
+ { ...op.replaceOne, multi: false }
1063
+ );
1064
+ if (hasAtomicOperators(updateStatement.u)) {
1065
+ throw new MongoInvalidArgumentError('Replacement document must not use atomic operators');
1066
+ }
1067
+ return this.addToOperationsList(BatchType.UPDATE, updateStatement);
1068
+ }
1069
+
1070
+ if ('updateOne' in op) {
1071
+ if ('q' in op.updateOne) {
1072
+ throw new MongoInvalidArgumentError('Raw operations are not allowed');
1073
+ }
1074
+ const updateStatement = makeUpdateStatement(op.updateOne.filter, op.updateOne.update, {
1075
+ ...op.updateOne,
1076
+ multi: false
1077
+ });
1078
+ if (!hasAtomicOperators(updateStatement.u, this.bsonOptions)) {
1079
+ throw new MongoInvalidArgumentError('Update document requires atomic operators');
1080
+ }
1081
+ return this.addToOperationsList(BatchType.UPDATE, updateStatement);
1082
+ }
1083
+
1084
+ if ('updateMany' in op) {
1085
+ if ('q' in op.updateMany) {
1086
+ throw new MongoInvalidArgumentError('Raw operations are not allowed');
1087
+ }
1088
+ const updateStatement = makeUpdateStatement(op.updateMany.filter, op.updateMany.update, {
1089
+ ...op.updateMany,
1090
+ multi: true
1091
+ });
1092
+ if (!hasAtomicOperators(updateStatement.u, this.bsonOptions)) {
1093
+ throw new MongoInvalidArgumentError('Update document requires atomic operators');
1094
+ }
1095
+ return this.addToOperationsList(BatchType.UPDATE, updateStatement);
1096
+ }
1097
+ }
1098
+
1099
+ if ('deleteOne' in op) {
1100
+ if ('q' in op.deleteOne) {
1101
+ throw new MongoInvalidArgumentError('Raw operations are not allowed');
1102
+ }
1103
+ return this.addToOperationsList(
1104
+ BatchType.DELETE,
1105
+ makeDeleteStatement(op.deleteOne.filter, { ...op.deleteOne, limit: 1 })
1106
+ );
1107
+ }
1108
+
1109
+ if ('deleteMany' in op) {
1110
+ if ('q' in op.deleteMany) {
1111
+ throw new MongoInvalidArgumentError('Raw operations are not allowed');
1112
+ }
1113
+ return this.addToOperationsList(
1114
+ BatchType.DELETE,
1115
+ makeDeleteStatement(op.deleteMany.filter, { ...op.deleteMany, limit: 0 })
1116
+ );
1117
+ }
1118
+
1119
+ // otherwise an unknown operation was provided
1120
+ throw new MongoInvalidArgumentError(
1121
+ 'bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany'
1122
+ );
1123
+ }
1124
+
1125
+ get length(): number {
1126
+ return this.s.currentIndex;
1127
+ }
1128
+
1129
+ get bsonOptions(): BSONSerializeOptions {
1130
+ return this.s.bsonOptions;
1131
+ }
1132
+
1133
+ get writeConcern(): WriteConcern | undefined {
1134
+ return this.s.writeConcern;
1135
+ }
1136
+
1137
+ get batches(): Batch[] {
1138
+ const batches = [...this.s.batches];
1139
+ if (this.isOrdered) {
1140
+ if (this.s.currentBatch) batches.push(this.s.currentBatch);
1141
+ } else {
1142
+ if (this.s.currentInsertBatch) batches.push(this.s.currentInsertBatch);
1143
+ if (this.s.currentUpdateBatch) batches.push(this.s.currentUpdateBatch);
1144
+ if (this.s.currentRemoveBatch) batches.push(this.s.currentRemoveBatch);
1145
+ }
1146
+ return batches;
1147
+ }
1148
+
1149
+ async execute(options: BulkWriteOptions = {}): Promise<BulkWriteResult> {
1150
+ if (this.s.executed) {
1151
+ throw new MongoBatchReExecutionError();
1152
+ }
1153
+
1154
+ const writeConcern = WriteConcern.fromOptions(options);
1155
+ if (writeConcern) {
1156
+ this.s.writeConcern = writeConcern;
1157
+ }
1158
+
1159
+ // If we have current batch
1160
+ if (this.isOrdered) {
1161
+ if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch);
1162
+ } else {
1163
+ if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch);
1164
+ if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch);
1165
+ if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch);
1166
+ }
1167
+ // If we have no operations in the bulk raise an error
1168
+ if (this.s.batches.length === 0) {
1169
+ throw new MongoInvalidArgumentError('Invalid BulkOperation, Batch cannot be empty');
1170
+ }
1171
+
1172
+ this.s.executed = true;
1173
+ const finalOptions = resolveOptions(this.collection, { ...this.s.options, ...options });
1174
+
1175
+ // if there is no timeoutContext provided, create a timeoutContext and use it for
1176
+ // all batches in the bulk operation
1177
+ finalOptions.timeoutContext ??= TimeoutContext.create({
1178
+ session: finalOptions.session,
1179
+ timeoutMS: finalOptions.timeoutMS,
1180
+ serverSelectionTimeoutMS: this.collection.client.s.options.serverSelectionTimeoutMS,
1181
+ waitQueueTimeoutMS: this.collection.client.s.options.waitQueueTimeoutMS
1182
+ });
1183
+
1184
+ if (finalOptions.session == null) {
1185
+ // if there is not an explicit session provided to `execute()`, create
1186
+ // an implicit session and use that for all batches in the bulk operation
1187
+ return await this.collection.client.withSession({ explicit: false }, async session => {
1188
+ return await executeCommands(this, { ...finalOptions, session });
1189
+ });
1190
+ }
1191
+
1192
+ return await executeCommands(this, { ...finalOptions });
1193
+ }
1194
+
1195
+ /**
1196
+ * Handles the write error before executing commands
1197
+ * @internal
1198
+ */
1199
+ handleWriteError(writeResult: BulkWriteResult): void {
1200
+ if (this.s.bulkResult.writeErrors.length > 0) {
1201
+ const msg = this.s.bulkResult.writeErrors[0].errmsg
1202
+ ? this.s.bulkResult.writeErrors[0].errmsg
1203
+ : 'write operation failed';
1204
+
1205
+ throw new MongoBulkWriteError(
1206
+ {
1207
+ message: msg,
1208
+ code: this.s.bulkResult.writeErrors[0].code,
1209
+ writeErrors: this.s.bulkResult.writeErrors
1210
+ },
1211
+ writeResult
1212
+ );
1213
+ }
1214
+
1215
+ const writeConcernError = writeResult.getWriteConcernError();
1216
+ if (writeConcernError) {
1217
+ throw new MongoBulkWriteError(writeConcernError, writeResult);
1218
+ }
1219
+ }
1220
+
1221
+ abstract addToOperationsList(
1222
+ batchType: BatchType,
1223
+ document: Document | UpdateStatement | DeleteStatement
1224
+ ): this;
1225
+
1226
+ private shouldForceServerObjectId(): boolean {
1227
+ return (
1228
+ this.s.options.forceServerObjectId === true ||
1229
+ this.s.collection.db.options?.forceServerObjectId === true
1230
+ );
1231
+ }
1232
+ }
1233
+
1234
+ function isInsertBatch(batch: Batch): boolean {
1235
+ return batch.batchType === BatchType.INSERT;
1236
+ }
1237
+
1238
+ function isUpdateBatch(batch: Batch): batch is Batch<UpdateStatement> {
1239
+ return batch.batchType === BatchType.UPDATE;
1240
+ }
1241
+
1242
+ function isDeleteBatch(batch: Batch): batch is Batch<DeleteStatement> {
1243
+ return batch.batchType === BatchType.DELETE;
1244
+ }
1245
+
1246
+ function buildCurrentOp(bulkOp: BulkOperationBase): Document {
1247
+ let { currentOp } = bulkOp.s;
1248
+ bulkOp.s.currentOp = undefined;
1249
+ if (!currentOp) currentOp = {};
1250
+ return currentOp;
1251
+ }