@mongodb-js/compass-web 1.0.2 → 1.1.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 (28) hide show
  1. package/dist/112.cc6e81f79429e73c45e2.mjs +1 -0
  2. package/dist/260.22d04797e908a8464d8f.mjs +2 -0
  3. package/dist/302.21e186c638bb98594c8f.mjs +1 -0
  4. package/dist/318.e28eef3a6f052df2dd22.mjs +2 -0
  5. package/dist/{127.3d74d7292010279682c5.mjs → 641.9949264e344f753ec909.mjs} +12 -12
  6. package/dist/65.0f0eb2e998535a138203.mjs +2 -0
  7. package/dist/{560.e85e11aa098b341006f3.mjs → 797.f011900fbc0adc5fef75.mjs} +3 -3
  8. package/dist/{560.e85e11aa098b341006f3.mjs.LICENSE.txt → 797.f011900fbc0adc5fef75.mjs.LICENSE.txt} +9 -8
  9. package/dist/872.8e7d5b8a3b8fcff75118.mjs +2 -0
  10. package/dist/assets-manifest.json +10 -10
  11. package/dist/compass-web.mjs +3 -3
  12. package/dist/index-0b9a48a6.23a217523e1f14bb9fce.mjs +29 -0
  13. package/dist/index-bde52cb3.79ced92f5eb98874dbcb.mjs +1 -0
  14. package/dist/tsdoc-metadata.json +1 -1
  15. package/package.json +49 -47
  16. package/dist/106.e50960c29b57a8b92ec5.mjs +0 -2
  17. package/dist/14.4041757b6d1c01a732c6.mjs +0 -2
  18. package/dist/260.52fdf61d69ac2a2921dc.mjs +0 -2
  19. package/dist/302.34205d8fa79ef45d79b5.mjs +0 -1
  20. package/dist/318.da796d13247ed6c3c28b.mjs +0 -2
  21. package/dist/717.32457884d95d961bc576.mjs +0 -1
  22. package/dist/index-0b9a48a6.8808d00d1b8145c52728.mjs +0 -29
  23. package/dist/index-bde52cb3.6f51548cb3f25ef57945.mjs +0 -1
  24. /package/dist/{260.52fdf61d69ac2a2921dc.mjs.LICENSE.txt → 260.22d04797e908a8464d8f.mjs.LICENSE.txt} +0 -0
  25. /package/dist/{318.da796d13247ed6c3c28b.mjs.LICENSE.txt → 318.e28eef3a6f052df2dd22.mjs.LICENSE.txt} +0 -0
  26. /package/dist/{127.3d74d7292010279682c5.mjs.LICENSE.txt → 641.9949264e344f753ec909.mjs.LICENSE.txt} +0 -0
  27. /package/dist/{14.4041757b6d1c01a732c6.mjs.LICENSE.txt → 65.0f0eb2e998535a138203.mjs.LICENSE.txt} +0 -0
  28. /package/dist/{106.e50960c29b57a8b92ec5.mjs.LICENSE.txt → 872.8e7d5b8a3b8fcff75118.mjs.LICENSE.txt} +0 -0
@@ -1 +0,0 @@
1
- export const __webpack_esm_id__=302;export const __webpack_esm_ids__=[302];export const __webpack_esm_modules__={97:function(e,t,o){var n,r=o(15088).process,i=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[t.length]=o);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o=n(e),r=0;r<o.length;r++)"default"!==o[r]&&i(t,e,o[r]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.default=function({connectionString:e,buildInfo:t,atlasVersion:o,resolvedHostname:n,isLocalAtlas:i,serverName:s="unknown"}){const a=e?.searchParams.get("authMechanism")??void 0,l=e?.toString()??"";t??={};const{isDataLake:d,dlVersion:u}=c.getDataLake(t),{serverOs:h,serverArch:m}=c.getBuildEnv(t),p=!!o?.atlasVersion||c.isAtlas(l);return{...(g=n||l,g?c.isLocalhost(g)?{is_localhost:!0,is_do_url:!1,is_atlas_url:!1}:c.isDigitalOcean(g)?{is_localhost:!1,is_do_url:!0,is_atlas_url:!1}:{is_localhost:!1,is_do_url:!1,is_atlas_url:c.isAtlas(g)}:{is_localhost:!1,is_do_url:!1,is_atlas_url:!1}),is_atlas:p,server_version:t.version,node_version:r.version,server_os:h||void 0,uri:l,server_arch:m||void 0,is_enterprise:c.isEnterprise(t),auth_type:a,is_data_federation:d,is_stream:c.isAtlasStream(l),dl_version:u||void 0,atlas_version:o?.atlasVersion??null,is_genuine:"mongodb"===s||"unknown"===s,non_genuine_server_name:s,is_local_atlas:i};var g};const c=a(o(39446))},183:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoRuntimeError=t.MongoParseError=t.MongoOperationTimeoutError=t.MongoOIDCError=t.MongoNotConnectedError=t.MongoNetworkTimeoutError=t.MongoNetworkError=t.MongoMissingDependencyError=t.MongoMissingCredentialsError=t.MongoKerberosError=t.MongoInvalidArgumentError=t.MongoGridFSStreamError=t.MongoGridFSChunkError=t.MongoGCPError=t.MongoExpiredSessionError=t.MongoError=t.MongoDriverError=t.MongoDecompressionError=t.MongoCursorInUseError=t.MongoCursorExhaustedError=t.MongoCompatibilityError=t.MongoClientClosedError=t.MongoClientBulkWriteExecutionError=t.MongoClientBulkWriteError=t.MongoClientBulkWriteCursorError=t.MongoChangeStreamError=t.MongoBatchReExecutionError=t.MongoAzureError=t.MongoAWSError=t.MongoAPIError=t.ExplainableCursor=t.ChangeStreamCursor=t.ClientEncryption=t.MongoBulkWriteError=t.UUID=t.Timestamp=t.ObjectId=t.MinKey=t.MaxKey=t.Long=t.Int32=t.Double=t.Decimal128=t.DBRef=t.Code=t.BSONType=t.BSONSymbol=t.BSONRegExp=t.Binary=t.BSON=void 0,t.CommandStartedEvent=t.CommandFailedEvent=t.WriteConcern=t.ReadPreference=t.ReadConcern=t.TopologyType=t.ServerType=t.ReadPreferenceMode=t.ReadConcernLevel=t.ProfilingLevel=t.ReturnDocument=t.SeverityLevel=t.MongoLoggableComponent=t.ServerApiVersion=t.ExplainVerbosity=t.MongoErrorLabel=t.CursorTimeoutMode=t.CURSOR_FLAGS=t.Compressor=t.AuthMechanism=t.GSSAPICanonicalizationValue=t.AutoEncryptionLoggerLevel=t.BatchType=t.UnorderedBulkOperation=t.OrderedBulkOperation=t.MongoClient=t.ListIndexesCursor=t.ListCollectionsCursor=t.GridFSBucketWriteStream=t.GridFSBucketReadStream=t.GridFSBucket=t.FindCursor=t.Db=t.Collection=t.ClientSession=t.ChangeStream=t.CancellationToken=t.AggregationCursor=t.Admin=t.AbstractCursor=t.MongoWriteConcernError=t.MongoUnexpectedServerResponseError=t.MongoTransactionError=t.MongoTopologyClosedError=t.MongoTailableCursorError=t.MongoSystemError=t.MongoStalePrimaryError=t.MongoServerSelectionError=t.MongoServerError=t.MongoServerClosedError=void 0,t.MongoClientAuthProviders=t.MongoCryptKMSRequestNetworkTimeoutError=t.MongoCryptInvalidArgumentError=t.MongoCryptError=t.MongoCryptCreateEncryptedCollectionError=t.MongoCryptCreateDataKeyError=t.MongoCryptAzureKMSRequestError=t.SrvPollingEvent=t.WaitingForSuitableServerEvent=t.ServerSelectionSucceededEvent=t.ServerSelectionStartedEvent=t.ServerSelectionFailedEvent=t.ServerSelectionEvent=t.TopologyOpeningEvent=t.TopologyDescriptionChangedEvent=t.TopologyClosedEvent=t.ServerOpeningEvent=t.ServerHeartbeatSucceededEvent=t.ServerHeartbeatStartedEvent=t.ServerHeartbeatFailedEvent=t.ServerDescriptionChangedEvent=t.ServerClosedEvent=t.ConnectionReadyEvent=t.ConnectionPoolReadyEvent=t.ConnectionPoolMonitoringEvent=t.ConnectionPoolCreatedEvent=t.ConnectionPoolClosedEvent=t.ConnectionPoolClearedEvent=t.ConnectionCreatedEvent=t.ConnectionClosedEvent=t.ConnectionCheckOutStartedEvent=t.ConnectionCheckOutFailedEvent=t.ConnectionCheckedOutEvent=t.ConnectionCheckedInEvent=t.CommandSucceededEvent=void 0;const n=o(80568);Object.defineProperty(t,"Admin",{enumerable:!0,get:function(){return n.Admin}});const r=o(80529);Object.defineProperty(t,"OrderedBulkOperation",{enumerable:!0,get:function(){return r.OrderedBulkOperation}});const i=o(32328);Object.defineProperty(t,"UnorderedBulkOperation",{enumerable:!0,get:function(){return i.UnorderedBulkOperation}});const s=o(53373);Object.defineProperty(t,"ChangeStream",{enumerable:!0,get:function(){return s.ChangeStream}});const a=o(53975);Object.defineProperty(t,"Collection",{enumerable:!0,get:function(){return a.Collection}});const c=o(40927);Object.defineProperty(t,"AbstractCursor",{enumerable:!0,get:function(){return c.AbstractCursor}});const l=o(13237);Object.defineProperty(t,"AggregationCursor",{enumerable:!0,get:function(){return l.AggregationCursor}});const d=o(12668);Object.defineProperty(t,"FindCursor",{enumerable:!0,get:function(){return d.FindCursor}});const u=o(85407);Object.defineProperty(t,"ListCollectionsCursor",{enumerable:!0,get:function(){return u.ListCollectionsCursor}});const h=o(10176);Object.defineProperty(t,"ListIndexesCursor",{enumerable:!0,get:function(){return h.ListIndexesCursor}});const m=o(3137);Object.defineProperty(t,"Db",{enumerable:!0,get:function(){return m.Db}});const p=o(2419);Object.defineProperty(t,"GridFSBucket",{enumerable:!0,get:function(){return p.GridFSBucket}});const g=o(49879);Object.defineProperty(t,"GridFSBucketReadStream",{enumerable:!0,get:function(){return g.GridFSBucketReadStream}});const f=o(44714);Object.defineProperty(t,"GridFSBucketWriteStream",{enumerable:!0,get:function(){return f.GridFSBucketWriteStream}});const S=o(88757);Object.defineProperty(t,"MongoClient",{enumerable:!0,get:function(){return S.MongoClient}});const E=o(72361);Object.defineProperty(t,"CancellationToken",{enumerable:!0,get:function(){return E.CancellationToken}});const y=o(86098);Object.defineProperty(t,"ClientSession",{enumerable:!0,get:function(){return y.ClientSession}});var b=o(77953);Object.defineProperty(t,"BSON",{enumerable:!0,get:function(){return b.BSON}});var O=o(77953);Object.defineProperty(t,"Binary",{enumerable:!0,get:function(){return O.Binary}}),Object.defineProperty(t,"BSONRegExp",{enumerable:!0,get:function(){return O.BSONRegExp}}),Object.defineProperty(t,"BSONSymbol",{enumerable:!0,get:function(){return O.BSONSymbol}}),Object.defineProperty(t,"BSONType",{enumerable:!0,get:function(){return O.BSONType}}),Object.defineProperty(t,"Code",{enumerable:!0,get:function(){return O.Code}}),Object.defineProperty(t,"DBRef",{enumerable:!0,get:function(){return O.DBRef}}),Object.defineProperty(t,"Decimal128",{enumerable:!0,get:function(){return O.Decimal128}}),Object.defineProperty(t,"Double",{enumerable:!0,get:function(){return O.Double}}),Object.defineProperty(t,"Int32",{enumerable:!0,get:function(){return O.Int32}}),Object.defineProperty(t,"Long",{enumerable:!0,get:function(){return O.Long}}),Object.defineProperty(t,"MaxKey",{enumerable:!0,get:function(){return O.MaxKey}}),Object.defineProperty(t,"MinKey",{enumerable:!0,get:function(){return O.MinKey}}),Object.defineProperty(t,"ObjectId",{enumerable:!0,get:function(){return O.ObjectId}}),Object.defineProperty(t,"Timestamp",{enumerable:!0,get:function(){return O.Timestamp}}),Object.defineProperty(t,"UUID",{enumerable:!0,get:function(){return O.UUID}});var C=o(82403);Object.defineProperty(t,"MongoBulkWriteError",{enumerable:!0,get:function(){return C.MongoBulkWriteError}});var M=o(46352);Object.defineProperty(t,"ClientEncryption",{enumerable:!0,get:function(){return M.ClientEncryption}});var T=o(50700);Object.defineProperty(t,"ChangeStreamCursor",{enumerable:!0,get:function(){return T.ChangeStreamCursor}});var w=o(44058);Object.defineProperty(t,"ExplainableCursor",{enumerable:!0,get:function(){return w.ExplainableCursor}});var v=o(36997);Object.defineProperty(t,"MongoAPIError",{enumerable:!0,get:function(){return v.MongoAPIError}}),Object.defineProperty(t,"MongoAWSError",{enumerable:!0,get:function(){return v.MongoAWSError}}),Object.defineProperty(t,"MongoAzureError",{enumerable:!0,get:function(){return v.MongoAzureError}}),Object.defineProperty(t,"MongoBatchReExecutionError",{enumerable:!0,get:function(){return v.MongoBatchReExecutionError}}),Object.defineProperty(t,"MongoChangeStreamError",{enumerable:!0,get:function(){return v.MongoChangeStreamError}}),Object.defineProperty(t,"MongoClientBulkWriteCursorError",{enumerable:!0,get:function(){return v.MongoClientBulkWriteCursorError}}),Object.defineProperty(t,"MongoClientBulkWriteError",{enumerable:!0,get:function(){return v.MongoClientBulkWriteError}}),Object.defineProperty(t,"MongoClientBulkWriteExecutionError",{enumerable:!0,get:function(){return v.MongoClientBulkWriteExecutionError}}),Object.defineProperty(t,"MongoClientClosedError",{enumerable:!0,get:function(){return v.MongoClientClosedError}}),Object.defineProperty(t,"MongoCompatibilityError",{enumerable:!0,get:function(){return v.MongoCompatibilityError}}),Object.defineProperty(t,"MongoCursorExhaustedError",{enumerable:!0,get:function(){return v.MongoCursorExhaustedError}}),Object.defineProperty(t,"MongoCursorInUseError",{enumerable:!0,get:function(){return v.MongoCursorInUseError}}),Object.defineProperty(t,"MongoDecompressionError",{enumerable:!0,get:function(){return v.MongoDecompressionError}}),Object.defineProperty(t,"MongoDriverError",{enumerable:!0,get:function(){return v.MongoDriverError}}),Object.defineProperty(t,"MongoError",{enumerable:!0,get:function(){return v.MongoError}}),Object.defineProperty(t,"MongoExpiredSessionError",{enumerable:!0,get:function(){return v.MongoExpiredSessionError}}),Object.defineProperty(t,"MongoGCPError",{enumerable:!0,get:function(){return v.MongoGCPError}}),Object.defineProperty(t,"MongoGridFSChunkError",{enumerable:!0,get:function(){return v.MongoGridFSChunkError}}),Object.defineProperty(t,"MongoGridFSStreamError",{enumerable:!0,get:function(){return v.MongoGridFSStreamError}}),Object.defineProperty(t,"MongoInvalidArgumentError",{enumerable:!0,get:function(){return v.MongoInvalidArgumentError}}),Object.defineProperty(t,"MongoKerberosError",{enumerable:!0,get:function(){return v.MongoKerberosError}}),Object.defineProperty(t,"MongoMissingCredentialsError",{enumerable:!0,get:function(){return v.MongoMissingCredentialsError}}),Object.defineProperty(t,"MongoMissingDependencyError",{enumerable:!0,get:function(){return v.MongoMissingDependencyError}}),Object.defineProperty(t,"MongoNetworkError",{enumerable:!0,get:function(){return v.MongoNetworkError}}),Object.defineProperty(t,"MongoNetworkTimeoutError",{enumerable:!0,get:function(){return v.MongoNetworkTimeoutError}}),Object.defineProperty(t,"MongoNotConnectedError",{enumerable:!0,get:function(){return v.MongoNotConnectedError}}),Object.defineProperty(t,"MongoOIDCError",{enumerable:!0,get:function(){return v.MongoOIDCError}}),Object.defineProperty(t,"MongoOperationTimeoutError",{enumerable:!0,get:function(){return v.MongoOperationTimeoutError}}),Object.defineProperty(t,"MongoParseError",{enumerable:!0,get:function(){return v.MongoParseError}}),Object.defineProperty(t,"MongoRuntimeError",{enumerable:!0,get:function(){return v.MongoRuntimeError}}),Object.defineProperty(t,"MongoServerClosedError",{enumerable:!0,get:function(){return v.MongoServerClosedError}}),Object.defineProperty(t,"MongoServerError",{enumerable:!0,get:function(){return v.MongoServerError}}),Object.defineProperty(t,"MongoServerSelectionError",{enumerable:!0,get:function(){return v.MongoServerSelectionError}}),Object.defineProperty(t,"MongoStalePrimaryError",{enumerable:!0,get:function(){return v.MongoStalePrimaryError}}),Object.defineProperty(t,"MongoSystemError",{enumerable:!0,get:function(){return v.MongoSystemError}}),Object.defineProperty(t,"MongoTailableCursorError",{enumerable:!0,get:function(){return v.MongoTailableCursorError}}),Object.defineProperty(t,"MongoTopologyClosedError",{enumerable:!0,get:function(){return v.MongoTopologyClosedError}}),Object.defineProperty(t,"MongoTransactionError",{enumerable:!0,get:function(){return v.MongoTransactionError}}),Object.defineProperty(t,"MongoUnexpectedServerResponseError",{enumerable:!0,get:function(){return v.MongoUnexpectedServerResponseError}}),Object.defineProperty(t,"MongoWriteConcernError",{enumerable:!0,get:function(){return v.MongoWriteConcernError}});var R=o(82403);Object.defineProperty(t,"BatchType",{enumerable:!0,get:function(){return R.BatchType}});var A=o(9095);Object.defineProperty(t,"AutoEncryptionLoggerLevel",{enumerable:!0,get:function(){return A.AutoEncryptionLoggerLevel}});var _=o(21427);Object.defineProperty(t,"GSSAPICanonicalizationValue",{enumerable:!0,get:function(){return _.GSSAPICanonicalizationValue}});var I=o(65070);Object.defineProperty(t,"AuthMechanism",{enumerable:!0,get:function(){return I.AuthMechanism}});var N=o(73738);Object.defineProperty(t,"Compressor",{enumerable:!0,get:function(){return N.Compressor}});var x=o(40927);Object.defineProperty(t,"CURSOR_FLAGS",{enumerable:!0,get:function(){return x.CURSOR_FLAGS}}),Object.defineProperty(t,"CursorTimeoutMode",{enumerable:!0,get:function(){return x.CursorTimeoutMode}});var k=o(36997);Object.defineProperty(t,"MongoErrorLabel",{enumerable:!0,get:function(){return k.MongoErrorLabel}});var P=o(27272);Object.defineProperty(t,"ExplainVerbosity",{enumerable:!0,get:function(){return P.ExplainVerbosity}});var D=o(88757);Object.defineProperty(t,"ServerApiVersion",{enumerable:!0,get:function(){return D.ServerApiVersion}});var L=o(60866);Object.defineProperty(t,"MongoLoggableComponent",{enumerable:!0,get:function(){return L.MongoLoggableComponent}}),Object.defineProperty(t,"SeverityLevel",{enumerable:!0,get:function(){return L.SeverityLevel}});var B=o(95174);Object.defineProperty(t,"ReturnDocument",{enumerable:!0,get:function(){return B.ReturnDocument}});var j=o(53482);Object.defineProperty(t,"ProfilingLevel",{enumerable:!0,get:function(){return j.ProfilingLevel}});var U=o(86552);Object.defineProperty(t,"ReadConcernLevel",{enumerable:!0,get:function(){return U.ReadConcernLevel}});var W=o(74891);Object.defineProperty(t,"ReadPreferenceMode",{enumerable:!0,get:function(){return W.ReadPreferenceMode}});var F=o(90648);Object.defineProperty(t,"ServerType",{enumerable:!0,get:function(){return F.ServerType}}),Object.defineProperty(t,"TopologyType",{enumerable:!0,get:function(){return F.TopologyType}});var V=o(86552);Object.defineProperty(t,"ReadConcern",{enumerable:!0,get:function(){return V.ReadConcern}});var z=o(74891);Object.defineProperty(t,"ReadPreference",{enumerable:!0,get:function(){return z.ReadPreference}});var G=o(71259);Object.defineProperty(t,"WriteConcern",{enumerable:!0,get:function(){return G.WriteConcern}});var $=o(60449);Object.defineProperty(t,"CommandFailedEvent",{enumerable:!0,get:function(){return $.CommandFailedEvent}}),Object.defineProperty(t,"CommandStartedEvent",{enumerable:!0,get:function(){return $.CommandStartedEvent}}),Object.defineProperty(t,"CommandSucceededEvent",{enumerable:!0,get:function(){return $.CommandSucceededEvent}});var H=o(78948);Object.defineProperty(t,"ConnectionCheckedInEvent",{enumerable:!0,get:function(){return H.ConnectionCheckedInEvent}}),Object.defineProperty(t,"ConnectionCheckedOutEvent",{enumerable:!0,get:function(){return H.ConnectionCheckedOutEvent}}),Object.defineProperty(t,"ConnectionCheckOutFailedEvent",{enumerable:!0,get:function(){return H.ConnectionCheckOutFailedEvent}}),Object.defineProperty(t,"ConnectionCheckOutStartedEvent",{enumerable:!0,get:function(){return H.ConnectionCheckOutStartedEvent}}),Object.defineProperty(t,"ConnectionClosedEvent",{enumerable:!0,get:function(){return H.ConnectionClosedEvent}}),Object.defineProperty(t,"ConnectionCreatedEvent",{enumerable:!0,get:function(){return H.ConnectionCreatedEvent}}),Object.defineProperty(t,"ConnectionPoolClearedEvent",{enumerable:!0,get:function(){return H.ConnectionPoolClearedEvent}}),Object.defineProperty(t,"ConnectionPoolClosedEvent",{enumerable:!0,get:function(){return H.ConnectionPoolClosedEvent}}),Object.defineProperty(t,"ConnectionPoolCreatedEvent",{enumerable:!0,get:function(){return H.ConnectionPoolCreatedEvent}}),Object.defineProperty(t,"ConnectionPoolMonitoringEvent",{enumerable:!0,get:function(){return H.ConnectionPoolMonitoringEvent}}),Object.defineProperty(t,"ConnectionPoolReadyEvent",{enumerable:!0,get:function(){return H.ConnectionPoolReadyEvent}}),Object.defineProperty(t,"ConnectionReadyEvent",{enumerable:!0,get:function(){return H.ConnectionReadyEvent}});var K=o(86348);Object.defineProperty(t,"ServerClosedEvent",{enumerable:!0,get:function(){return K.ServerClosedEvent}}),Object.defineProperty(t,"ServerDescriptionChangedEvent",{enumerable:!0,get:function(){return K.ServerDescriptionChangedEvent}}),Object.defineProperty(t,"ServerHeartbeatFailedEvent",{enumerable:!0,get:function(){return K.ServerHeartbeatFailedEvent}}),Object.defineProperty(t,"ServerHeartbeatStartedEvent",{enumerable:!0,get:function(){return K.ServerHeartbeatStartedEvent}}),Object.defineProperty(t,"ServerHeartbeatSucceededEvent",{enumerable:!0,get:function(){return K.ServerHeartbeatSucceededEvent}}),Object.defineProperty(t,"ServerOpeningEvent",{enumerable:!0,get:function(){return K.ServerOpeningEvent}}),Object.defineProperty(t,"TopologyClosedEvent",{enumerable:!0,get:function(){return K.TopologyClosedEvent}}),Object.defineProperty(t,"TopologyDescriptionChangedEvent",{enumerable:!0,get:function(){return K.TopologyDescriptionChangedEvent}}),Object.defineProperty(t,"TopologyOpeningEvent",{enumerable:!0,get:function(){return K.TopologyOpeningEvent}});var q=o(61347);Object.defineProperty(t,"ServerSelectionEvent",{enumerable:!0,get:function(){return q.ServerSelectionEvent}}),Object.defineProperty(t,"ServerSelectionFailedEvent",{enumerable:!0,get:function(){return q.ServerSelectionFailedEvent}}),Object.defineProperty(t,"ServerSelectionStartedEvent",{enumerable:!0,get:function(){return q.ServerSelectionStartedEvent}}),Object.defineProperty(t,"ServerSelectionSucceededEvent",{enumerable:!0,get:function(){return q.ServerSelectionSucceededEvent}}),Object.defineProperty(t,"WaitingForSuitableServerEvent",{enumerable:!0,get:function(){return q.WaitingForSuitableServerEvent}});var Y=o(39272);Object.defineProperty(t,"SrvPollingEvent",{enumerable:!0,get:function(){return Y.SrvPollingEvent}});var Q=o(64578);Object.defineProperty(t,"MongoCryptAzureKMSRequestError",{enumerable:!0,get:function(){return Q.MongoCryptAzureKMSRequestError}}),Object.defineProperty(t,"MongoCryptCreateDataKeyError",{enumerable:!0,get:function(){return Q.MongoCryptCreateDataKeyError}}),Object.defineProperty(t,"MongoCryptCreateEncryptedCollectionError",{enumerable:!0,get:function(){return Q.MongoCryptCreateEncryptedCollectionError}}),Object.defineProperty(t,"MongoCryptError",{enumerable:!0,get:function(){return Q.MongoCryptError}}),Object.defineProperty(t,"MongoCryptInvalidArgumentError",{enumerable:!0,get:function(){return Q.MongoCryptInvalidArgumentError}}),Object.defineProperty(t,"MongoCryptKMSRequestNetworkTimeoutError",{enumerable:!0,get:function(){return Q.MongoCryptKMSRequestNetworkTimeoutError}});var X=o(30427);Object.defineProperty(t,"MongoClientAuthProviders",{enumerable:!0,get:function(){return X.MongoClientAuthProviders}})},2419:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GridFSBucket=void 0;const n=o(36997),r=o(72361),i=o(33628),s=o(30306),a=o(71259),c=o(49879),l=o(44714),d={bucketName:"fs",chunkSizeBytes:261120};class u extends r.TypedEventEmitter{static{this.INDEX="index"}constructor(e,t){super(),this.on("error",s.noop),this.setMaxListeners(0);const o=(0,s.resolveOptions)(e,{...d,...t,writeConcern:a.WriteConcern.fromOptions(t)});this.s={db:e,options:o,_chunksCollection:e.collection(o.bucketName+".chunks"),_filesCollection:e.collection(o.bucketName+".files"),checkedIndexes:!1,calledOpenUploadStream:!1}}openUploadStream(e,t){return new l.GridFSBucketWriteStream(this,e,{timeoutMS:this.s.options.timeoutMS,...t})}openUploadStreamWithId(e,t,o){return new l.GridFSBucketWriteStream(this,t,{timeoutMS:this.s.options.timeoutMS,...o,id:e})}openDownloadStream(e,t){return new c.GridFSBucketReadStream(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,{_id:e},{timeoutMS:this.s.options.timeoutMS,...t})}async delete(e,t){const{timeoutMS:o}=(0,s.resolveOptions)(this.s.db,t);let r;o&&(r=new i.CSOTTimeoutContext({timeoutMS:o,serverSelectionTimeoutMS:this.s.db.client.s.options.serverSelectionTimeoutMS}));const{deletedCount:a}=await this.s._filesCollection.deleteOne({_id:e},{timeoutMS:r?.remainingTimeMS}),c=r?.remainingTimeMS;if(null!=c&&c<=0)throw new n.MongoOperationTimeoutError(`Timed out after ${o}ms`);if(await this.s._chunksCollection.deleteMany({files_id:e},{timeoutMS:c}),0===a)throw new n.MongoRuntimeError(`File not found for id ${e}`)}find(e={},t={}){return this.s._filesCollection.find(e,t)}openDownloadStreamByName(e,t){let o,n={uploadDate:-1};return t&&null!=t.revision&&(t.revision>=0?(n={uploadDate:1},o=t.revision):o=-t.revision-1),new c.GridFSBucketReadStream(this.s._chunksCollection,this.s._filesCollection,this.s.options.readPreference,{filename:e},{timeoutMS:this.s.options.timeoutMS,...t,sort:n,skip:o})}async rename(e,t,o){const r={_id:e},i={$set:{filename:t}},{matchedCount:s}=await this.s._filesCollection.updateOne(r,i,o);if(0===s)throw new n.MongoRuntimeError(`File with id ${e} not found`)}async drop(e){const{timeoutMS:t}=(0,s.resolveOptions)(this.s.db,e);let o;if(t&&(o=new i.CSOTTimeoutContext({timeoutMS:t,serverSelectionTimeoutMS:this.s.db.client.s.options.serverSelectionTimeoutMS})),o){await this.s._filesCollection.drop({timeoutMS:o.remainingTimeMS});const e=o.getRemainingTimeMSOrThrow(`Timed out after ${t}ms`);await this.s._chunksCollection.drop({timeoutMS:e})}else await this.s._filesCollection.drop(),await this.s._chunksCollection.drop()}}t.GridFSBucket=u},2560:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteExecutor=void 0;const n=o(40927),r=o(76203),i=o(36997),s=o(33628),a=o(30306),c=o(71259),l=o(39131),d=o(78817),u=o(91200),h=o(44820);t.ClientBulkWriteExecutor=class{constructor(e,t,o){if(0===t.length)throw new i.MongoClientBulkWriteExecutionError("No client bulk write models were provided.");if(this.client=e,this.operations=t,this.options={ordered:!0,bypassDocumentValidation:!1,verboseResults:!1,...o},this.options.writeConcern||(this.options.writeConcern=c.WriteConcern.fromOptions(this.client.s.options)),0===this.options.writeConcern?.w){if(this.options.verboseResults)throw new i.MongoInvalidArgumentError("Cannot request unacknowledged write concern and verbose results");if(this.options.ordered)throw new i.MongoInvalidArgumentError("Cannot request unacknowledged write concern and ordered writes")}}async execute(){const e=this.client.s.options.pkFactory,t=new u.ClientBulkWriteCommandBuilder(this.operations,this.options,e),o=(0,a.resolveTimeoutOptions)(this.client,this.options),c=s.TimeoutContext.create(o);if(0===this.options.writeConcern?.w){for(;t.hasNextBatch();){const e=new d.ClientBulkWriteOperation(t,this.options);await(0,l.executeOperation)(this.client,e,c)}return h.ClientBulkWriteResultsMerger.unacknowledged()}{const e=new h.ClientBulkWriteResultsMerger(this.options);for(;t.hasNextBatch();){const s=new n.CursorTimeoutContext(c,Symbol()),a={...this.options,timeoutContext:s,...null!=o.timeoutMS&&{timeoutMode:n.CursorTimeoutMode.LIFETIME}},l=new r.ClientBulkWriteCursor(this.client,t,a);try{await e.merge(l)}catch(t){if(t instanceof i.MongoServerError&&!(t instanceof i.MongoClientBulkWriteError)){const o=new i.MongoClientBulkWriteError({message:"Mongo client bulk write encountered an error during execution"});throw o.cause=t,o.partialResult=e.bulkWriteResult,o}throw t}}if(e.writeConcernErrors.length>0||e.writeErrors.size>0){const t=new i.MongoClientBulkWriteError({message:"Mongo client bulk write encountered errors during execution."});throw t.writeConcernErrors=e.writeConcernErrors,t.writeErrors=e.writeErrors,t.partialResult=e.bulkWriteResult,t}return e.bulkWriteResult}}}},3137:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Db=void 0;const n=o(80568),r=o(77953),i=o(53373),s=o(53975),a=o(34842),c=o(13237),l=o(85407),d=o(18370),u=o(36997),h=o(84715),m=o(45249),p=o(39131),g=o(15002),f=o(95157),S=o(85052),E=o(75878),y=o(9405),b=o(53482),O=o(71789),C=o(86552),M=o(74891),T=o(30306),w=o(71259),v=["writeConcern","readPreference","readPreferenceTags","native_parser","forceServerObjectId","pkFactory","serializeFunctions","raw","authSource","ignoreUndefined","readConcern","retryMiliSeconds","numberOfRetries","useBigInt64","promoteBuffers","promoteLongs","bsonRegExp","enableUtf8Validation","promoteValues","compression","retryWrites","timeoutMS"];class R{static{this.SYSTEM_NAMESPACE_COLLECTION=a.SYSTEM_NAMESPACE_COLLECTION}static{this.SYSTEM_INDEX_COLLECTION=a.SYSTEM_INDEX_COLLECTION}static{this.SYSTEM_PROFILE_COLLECTION=a.SYSTEM_PROFILE_COLLECTION}static{this.SYSTEM_USER_COLLECTION=a.SYSTEM_USER_COLLECTION}static{this.SYSTEM_COMMAND_COLLECTION=a.SYSTEM_COMMAND_COLLECTION}static{this.SYSTEM_JS_COLLECTION=a.SYSTEM_JS_COLLECTION}constructor(e,t,o){if(o=o??{},o=(0,T.filterOptions)(o,v),"string"==typeof t&&t.includes("."))throw new u.MongoInvalidArgumentError("Database names cannot contain the character '.'");this.s={options:o,readPreference:M.ReadPreference.fromOptions(o),bsonOptions:(0,r.resolveBSONOptions)(o,e),pkFactory:o?.pkFactory??T.DEFAULT_PK_FACTORY,readConcern:C.ReadConcern.fromOptions(o),writeConcern:w.WriteConcern.fromOptions(o),namespace:new T.MongoDBNamespace(t)},this.client=e}get databaseName(){return this.s.namespace.db}get options(){return this.s.options}get secondaryOk(){return"primary"!==this.s.readPreference?.preference||!1}get readConcern(){return this.s.readConcern}get readPreference(){return null==this.s.readPreference?this.client.readPreference:this.s.readPreference}get bsonOptions(){return this.s.bsonOptions}get writeConcern(){return this.s.writeConcern}get namespace(){return this.s.namespace.toString()}get timeoutMS(){return this.s.options?.timeoutMS}async createCollection(e,t){return t=(0,T.resolveOptions)(this,t),await(0,h.createCollections)(this,e,t)}async command(e,t){return await(0,p.executeOperation)(this.client,new y.RunCommandOperation(this.s.namespace,e,(0,T.resolveOptions)(void 0,{...(0,r.resolveBSONOptions)(t),timeoutMS:t?.timeoutMS??this.timeoutMS,session:t?.session,readPreference:t?.readPreference,signal:t?.signal})))}aggregate(e=[],t){return new c.AggregationCursor(this.client,this.s.namespace,e,(0,T.resolveOptions)(this,t))}admin(){return new n.Admin(this)}collection(e,t={}){if("function"==typeof t)throw new u.MongoInvalidArgumentError("The callback form of this helper has been removed.");return new s.Collection(this,e,(0,T.resolveOptions)(this,t))}async stats(e){return await(0,p.executeOperation)(this.client,new O.DbStatsOperation(this,(0,T.resolveOptions)(this,e)))}listCollections(e={},t={}){return new l.ListCollectionsCursor(this,e,(0,T.resolveOptions)(this,t))}async renameCollection(e,t,o){return await(0,p.executeOperation)(this.client,new E.RenameOperation(this.collection(e),t,(0,T.resolveOptions)(void 0,{...o,readPreference:M.ReadPreference.primary})))}async dropCollection(e,t){return t=(0,T.resolveOptions)(this,t),await(0,m.dropCollections)(this,e,t)}async dropDatabase(e){return await(0,p.executeOperation)(this.client,new m.DropDatabaseOperation(this,(0,T.resolveOptions)(this,e)))}async collections(e){return e=(0,T.resolveOptions)(this,e),(await this.listCollections({},{...e,nameOnly:!0}).toArray()).filter((({name:e})=>!e.includes("$"))).map((({name:e})=>new s.Collection(this,e,this.s.options)))}async createIndex(e,t,o){return(await(0,p.executeOperation)(this.client,g.CreateIndexesOperation.fromIndexSpecification(this,e,t,o)))[0]}async removeUser(e,t){return await(0,p.executeOperation)(this.client,new S.RemoveUserOperation(this,e,(0,T.resolveOptions)(this,t)))}async setProfilingLevel(e,t){return await(0,p.executeOperation)(this.client,new b.SetProfilingLevelOperation(this,e,(0,T.resolveOptions)(this,t)))}async profilingLevel(e){return await(0,p.executeOperation)(this.client,new f.ProfilingLevelOperation(this,(0,T.resolveOptions)(this,e)))}async indexInformation(e,t){return await this.collection(e).indexInformation((0,T.resolveOptions)(this,t))}watch(e=[],t={}){return Array.isArray(e)||(t=e,e=[]),new i.ChangeStream(this,e,(0,T.resolveOptions)(this,t))}runCursorCommand(e,t){return new d.RunCommandCursor(this,e,t)}}t.Db=R},3803:function(e,t,o){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.UnsupportedArgumentError=t.UnknownArgumentError=t.InvalidArgumentError=t.argMetadata=void 0,t.getArgumentMetadata=i,t.getDeprecatedArgsWithReplacement=function(e){const t={};for(const o of Object.keys(e.shape)){const n=i(e,o);n?.deprecationReplacement&&(t[o]=n.deprecationReplacement)}return t},t.getUnsupportedArgs=function(e){const t=[];for(const o of Object.keys(e.shape)){const n=i(e,o);n?.unsupported&&t.push(o)}return t};const r=n(o(99539));function i(e,o){const n=e.shape[o];if(n)return t.argMetadata.get(n)}t.argMetadata=r.default.registry();class s extends Error{constructor(e){super(e),this.name="InvalidArgumentError"}}t.InvalidArgumentError=s;class a extends Error{constructor(e){super(`Unknown argument: ${e}`),this.name="UnknownArgumentError",this.argument=e}}t.UnknownArgumentError=a;class c extends Error{constructor(e){super(`Unsupported argument: ${e}`),this.name="UnsupportedArgumentError",this.argument=e}}t.UnsupportedArgumentError=c},4530:(e,t,o)=>{var n=o(34110).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.ScramSHA256=t.ScramSHA1=void 0;const r=o(60757),i=o(97359),s=o(77953),a=o(36997),c=o(30306),l=o(68950),d=o(65070);class u extends l.AuthProvider{constructor(e){super(),this.cryptoMethod=e||"sha1"}async prepare(e,t){const o=this.cryptoMethod,n=t.credentials;if(!n)throw new a.MongoMissingCredentialsError("AuthContext must provide credentials.");const r=await(0,c.randomBytes)(24);return t.nonce=r,{...e,speculativeAuthenticate:{...p(o,n,r),db:n.source}}}async auth(e){const{reauthenticating:t,response:o}=e;return o?.speculativeAuthenticate&&!t?await g(this.cryptoMethod,o.speculativeAuthenticate,e):await async function(e,t){const{connection:o,credentials:n}=t;if(!n)throw new a.MongoMissingCredentialsError("AuthContext must provide credentials.");if(!t.nonce)throw new a.MongoInvalidArgumentError("AuthContext must contain a valid nonce property");const r=t.nonce,i=n.source,s=p(e,n,r),l=await o.command((0,c.ns)(`${i}.$cmd`),s,void 0);await g(e,l,t)}(this.cryptoMethod,e)}}function h(e){return e.replace("=","=3D").replace(",","=2C")}function m(e,t){return n.concat([n.from("n=","utf8"),n.from(e,"utf8"),n.from(",r=","utf8"),n.from(t.toString("base64"),"utf8")])}function p(e,t,o){const r=h(t.username);return{saslStart:1,mechanism:"sha1"===e?d.AuthMechanism.MONGODB_SCRAM_SHA1:d.AuthMechanism.MONGODB_SCRAM_SHA256,payload:new s.Binary(n.concat([n.from("n,,","utf8"),m(r,o)])),autoAuthorize:1,options:{skipEmptyExchange:!0}}}async function g(e,t,o){const l=o.connection,d=o.credentials;if(!d)throw new a.MongoMissingCredentialsError("AuthContext must provide credentials.");if(!o.nonce)throw new a.MongoInvalidArgumentError("Unable to continue SCRAM without valid nonce");const u=o.nonce,p=d.source,g=h(d.username),O=d.password,C="sha256"===e?(0,r.saslprep)(O):function(e,t){if("string"!=typeof e)throw new a.MongoInvalidArgumentError("Username must be a string");if("string"!=typeof t)throw new a.MongoInvalidArgumentError("Password must be a string");if(0===t.length)throw new a.MongoInvalidArgumentError("Password cannot be empty");let o;try{o=i.createHash("md5")}catch(e){if(i.getFips())throw new Error("Auth mechanism SCRAM-SHA-1 is not supported in FIPS mode");throw e}return o.update(`${e}:mongo:${t}`,"utf8"),o.digest("hex")}(g,O),M=n.isBuffer(t.payload)?new s.Binary(t.payload):t.payload,T=f(M),w=parseInt(T.i,10);if(w&&w<4096)throw new a.MongoRuntimeError(`Server returned an invalid iteration count ${w}`);const v=T.s,R=T.r;if(R.startsWith("nonce"))throw new a.MongoRuntimeError(`Server returned an invalid nonce: ${R}`);const A=`c=biws,r=${R}`,_=function(e,t,o,n){const r=[e,t.toString("base64"),o].join("_");if(null!=E[r])return E[r];const s=i.pbkdf2Sync(e,t,o,b[n],n);return y>=200&&(E={},y=0),E[r]=s,y+=1,s}(C,n.from(v,"base64"),w,e),I=S(e,_,"Client Key"),N=S(e,_,"Server Key"),x=(k=e,P=I,i.createHash(k).update(P).digest());var k,P;const D=[m(g,u),M.toString("utf8"),A].join(","),L=[A,`p=${function(e,t){n.isBuffer(e)||(e=n.from(e)),n.isBuffer(t)||(t=n.from(t));const o=Math.max(e.length,t.length),r=[];for(let n=0;n<o;n+=1)r.push(e[n]^t[n]);return n.from(r).toString("base64")}(I,S(e,x,D))}`].join(","),B=S(e,N,D),j={saslContinue:1,conversationId:t.conversationId,payload:new s.Binary(n.from(L))},U=await l.command((0,c.ns)(`${p}.$cmd`),j,void 0),W=f(U.payload);if(!function(e,t){if(e.length!==t.length)return!1;if("function"==typeof i.timingSafeEqual)return i.timingSafeEqual(e,t);let o=0;for(let n=0;n<e.length;n++)o|=e[n]^t[n];return 0===o}(n.from(W.v,"base64"),B))throw new a.MongoRuntimeError("Server returned an invalid signature");if(!1!==U.done)return;const F={saslContinue:1,conversationId:U.conversationId,payload:n.alloc(0)};await l.command((0,c.ns)(`${p}.$cmd`),F,void 0)}function f(e){const t={},o=e.toString("utf8").split(",");for(let e=0;e<o.length;e++){const n=(o[e].match(/^([^=]*)=(.*)$/)??[]).slice(1);t[n[0]]=n[1]}return t}function S(e,t,o){return i.createHmac(e,t).update(o).digest()}let E={},y=0;const b={sha256:32,sha1:20};t.ScramSHA1=class extends u{constructor(){super("sha1")}},t.ScramSHA256=class extends u{constructor(){super("sha256")}}},8138:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StateMachine=void 0;const n=o(75227),r=o(51390),i=o(15088),s=o(1568),a=o(77953),c=o(40927),l=o(98517),d=o(36997),u=o(33628),h=o(30306),m=o(46352),p=o(64578);let g=null;const f=new Map([[0,"MONGOCRYPT_CTX_ERROR"],[1,"MONGOCRYPT_CTX_NEED_MONGO_COLLINFO"],[2,"MONGOCRYPT_CTX_NEED_MONGO_MARKINGS"],[3,"MONGOCRYPT_CTX_NEED_MONGO_KEYS"],[7,"MONGOCRYPT_CTX_NEED_KMS_CREDENTIALS"],[4,"MONGOCRYPT_CTX_NEED_KMS"],[5,"MONGOCRYPT_CTX_READY"],[6,"MONGOCRYPT_CTX_DONE"]]),S=["tlsInsecure","tlsAllowInvalidCertificates","tlsAllowInvalidHostnames"];function E(e){i.env.MONGODB_CRYPT_DEBUG&&console.error(e)}let y;t.StateMachine=class{constructor(e,t=(0,a.pluckBSONSerializeOptions)(e)){this.options=e,this.bsonOptions=t}async execute(e,t,o){const n=e._keyVaultNamespace,r=e._keyVaultClient,i=e._metaDataClient,s=e._mongocryptdClient,c=e._mongocryptdManager;let l=null;const d=()=>t.status,u=()=>t.state;for(;6!==u()&&0!==u();)switch(o.signal?.throwIfAborted(),E(`[context#${t.id}] ${f.get(u())||u()}`),u()){case 1:{const e=(0,a.deserialize)(t.nextMongoOperation());if(!i)throw new p.MongoCryptError("unreachable state machine state: entered MONGOCRYPT_CTX_NEED_MONGO_COLLINFO but metadata client is undefined");const n=this.fetchCollectionInfo(i,t.ns,e,o);for await(const e of n)if(t.addMongoOperationResponse((0,a.serialize)(e)),0===u())break;if(0===u())break;t.finishMongoOperation();break}case 2:{const e=t.nextMongoOperation();if(0===u())break;if(!s)throw new p.MongoCryptError("unreachable state machine state: entered MONGOCRYPT_CTX_NEED_MONGO_MARKINGS but mongocryptdClient is undefined");const n=c?await c.withRespawn(this.markCommand.bind(this,s,t.ns,e,o)):await this.markCommand(s,t.ns,e,o);t.addMongoOperationResponse(n),t.finishMongoOperation();break}case 3:{const e=t.nextMongoOperation(),i=await this.fetchKeys(r,n,e,o);0===i.length&&(l=y??=(0,a.serialize)({v:[]}));for(const e of i)t.addMongoOperationResponse((0,a.serialize)(e));t.finishMongoOperation();break}case 7:{const o=await e.askForKMSCredentials();t.provideKMSProviders((0,a.serialize)(o));break}case 4:await Promise.all(this.requests(t,o)),t.finishKMSRequests();break;case 5:{const e=t.finalize();if(0===u()){const e=d().message||"Finalization error";throw new p.MongoCryptError(e)}l=e;break}default:throw new p.MongoCryptError(`Unknown state: ${u()}`)}if(0===u()||null==l){const e=d().message;throw e||E("unidentifiable error in MongoCrypt - received an error status from `libmongocrypt` but received no error message."),new p.MongoCryptError(e??"unidentifiable error in MongoCrypt - received an error status from `libmongocrypt` but received no error message.")}return l}async kmsRequest(e,t){const o=e.endpoint.split(":"),n=null!=o[1]?Number.parseInt(o[1],10):443,i={host:o[0],servername:o[0],port:n,...(0,m.autoSelectSocketOptions)(this.options.socketOptions||{})},a=e.message,c=new h.BufferPool;let f,S;function E(){for(const e of[S,f])e&&e.destroy()}function y(e){return new p.MongoCryptError("KMS request failed",{cause:e})}function b(){return new p.MongoCryptError("KMS request closed")}const O=this.options.tlsOptions;if(O){const t=e.kmsProvider,o=O[t];if(o){const e=this.validateTlsOptions(t,o);if(e)throw e;try{await this.setTlsOptions(o,i)}catch(e){throw y(e)}}}let C;try{if(this.options.proxyOptions&&this.options.proxyOptions.proxyHost){f=new r.Socket;const{promise:e,reject:t,resolve:o}=(0,h.promiseWithResolvers)();f.once("error",(e=>t(y(e)))).once("close",(()=>t(b()))).once("connect",(()=>o()));const n={...i,host:this.options.proxyOptions.proxyHost,port:this.options.proxyOptions.proxyPort||1080};f.connect(n),await e;try{g??=function(){if(null==g){const e=(0,l.getSocks)();if("kModuleError"in e)throw e.kModuleError;g=e}return g}(),i.socket=(await g.SocksClient.createConnection({existing_socket:f,command:"connect",destination:{host:i.host,port:i.port},proxy:{host:"iLoveJavaScript",port:0,type:5,userId:this.options.proxyOptions.proxyUsername,password:this.options.proxyOptions.proxyPassword}})).socket}catch(e){throw y(e)}}S=s.connect(i,(()=>{S.write(a)}));const{promise:o,reject:n,resolve:d}=(0,h.promiseWithResolvers)();C=(0,h.addAbortListener)(t?.signal,(function(){E(),n(this.reason)})),S.once("error",(e=>n(y(e)))).once("close",(()=>n(b()))).on("data",(t=>{for(c.append(t);e.bytesNeeded>0&&c.length;){const t=Math.min(e.bytesNeeded,c.length);e.addResponse(c.read(t))}e.bytesNeeded<=0&&d()})),await(t?.timeoutContext?.csotEnabled()?Promise.all([o,u.Timeout.expires(t.timeoutContext?.remainingTimeMS)]):o)}catch(e){if(e instanceof u.TimeoutError)throw new d.MongoOperationTimeoutError("KMS request timed out");throw e}finally{E(),C?.[h.kDispose]()}}*requests(e,t){for(let o=e.nextKMSRequest();null!=o;o=e.nextKMSRequest())yield this.kmsRequest(o,t)}validateTlsOptions(e,t){const o=Object.keys(t);for(const t of S)if(o.includes(t))return new p.MongoCryptError(`Insecure TLS options prohibited for ${e}: ${t}`)}async setTlsOptions(e,t){if(e.secureContext&&(t.secureContext=e.secureContext),e.tlsCertificateKeyFile){const o=await n.readFile(e.tlsCertificateKeyFile);t.cert=t.key=o}e.tlsCAFile&&(t.ca=await n.readFile(e.tlsCAFile)),e.tlsCertificateKeyFilePassword&&(t.passphrase=e.tlsCertificateKeyFilePassword)}fetchCollectionInfo(e,t,o,n){const{db:r}=h.MongoDBCollectionNamespace.fromString(t);return e.db(r).listCollections(o,{promoteLongs:!1,promoteValues:!1,timeoutContext:n?.timeoutContext&&new c.CursorTimeoutContext(n?.timeoutContext,Symbol()),signal:n?.signal,nameOnly:!1})}async markCommand(e,t,o,n){const{db:r}=h.MongoDBCollectionNamespace.fromString(t),i={promoteLongs:!1,promoteValues:!1},s=(0,a.deserialize)(o,i),c={timeoutMS:void 0,signal:void 0};n?.timeoutContext?.csotEnabled()&&(c.timeoutMS=n.timeoutContext.remainingTimeMS),n?.signal&&(c.signal=n.signal);const l=await e.db(r).command(s,{...i,...c});return(0,a.serialize)(l,this.bsonOptions)}fetchKeys(e,t,o,n){const{db:r,collection:i}=h.MongoDBCollectionNamespace.fromString(t),s={timeoutContext:void 0,signal:void 0};return null!=n?.timeoutContext&&(s.timeoutContext=new c.CursorTimeoutContext(n.timeoutContext,Symbol())),null!=n?.signal&&(s.signal=n.signal),e.db(r).collection(i,{readConcern:{level:"majority"}}).find((0,a.deserialize)(o),s).toArray()}}},9095:(e,t,o)=>{var n,r=o(34110).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.AutoEncrypter=t.AutoEncryptionLoggerLevel=void 0;const i=o(51390),s=o(77953),a=o(34842),c=o(98517),l=o(36997),d=o(88757),u=o(30306),h=o(46352),m=o(64578),p=o(59937),g=o(85744),f=o(8138);t.AutoEncryptionLoggerLevel=Object.freeze({FatalError:0,Error:1,Warning:2,Info:3,Trace:4});class S{static{n=a.kDecorateResult}static getMongoCrypt(){const e=(0,c.getMongoDBClientEncryption)();if("kModuleError"in e)throw e.kModuleError;return e.MongoCrypt}constructor(e,t){if(this[n]=!1,this._client=e,this._bypassEncryption=!0===t.bypassAutoEncryption,this._keyVaultNamespace=t.keyVaultNamespace||"admin.datakeys",this._keyVaultClient=t.keyVaultClient||e,this._metaDataClient=t.metadataClient||e,this._proxyOptions=t.proxyOptions||{},this._tlsOptions=t.tlsOptions||{},this._kmsProviders=t.kmsProviders||{},this._credentialProviders=t.credentialProviders,t.credentialProviders?.aws&&!(0,g.isEmptyCredentials)("aws",this._kmsProviders))throw new m.MongoCryptInvalidArgumentError("Can only provide a custom AWS credential provider when the state machine is configured for automatic AWS credential fetching");const o={errorWrapper:m.defaultErrorWrapper};t.schemaMap&&(o.schemaMap=r.isBuffer(t.schemaMap)?t.schemaMap:(0,s.serialize)(t.schemaMap)),t.encryptedFieldsMap&&(o.encryptedFieldsMap=r.isBuffer(t.encryptedFieldsMap)?t.encryptedFieldsMap:(0,s.serialize)(t.encryptedFieldsMap)),o.kmsProviders=r.isBuffer(this._kmsProviders)?this._kmsProviders:(0,s.serialize)(this._kmsProviders),t.options?.logger&&(o.logger=t.options.logger),t.extraOptions&&t.extraOptions.cryptSharedLibPath&&(o.cryptSharedLibPath=t.extraOptions.cryptSharedLibPath),t.bypassQueryAnalysis&&(o.bypassQueryAnalysis=t.bypassQueryAnalysis),null!=t.keyExpirationMS&&(o.keyExpirationMS=t.keyExpirationMS),this._bypassMongocryptdAndCryptShared=this._bypassEncryption||!!t.bypassQueryAnalysis,t.extraOptions&&t.extraOptions.cryptSharedLibSearchPaths?o.cryptSharedLibSearchPaths=t.extraOptions.cryptSharedLibSearchPaths:this._bypassMongocryptdAndCryptShared||(o.cryptSharedLibSearchPaths=["$SYSTEM"]);const a=S.getMongoCrypt();if(this._mongocrypt=new a(o),this._contextCounter=0,t.extraOptions&&t.extraOptions.cryptSharedLibRequired&&!this.cryptSharedLibVersionInfo)throw new m.MongoCryptInvalidArgumentError("`cryptSharedLibRequired` set but no crypt_shared library loaded");if(!this._bypassMongocryptdAndCryptShared&&!this.cryptSharedLibVersionInfo){this._mongocryptdManager=new p.MongocryptdManager(t.extraOptions);const e={serverSelectionTimeoutMS:1e4};null!=t.extraOptions&&"string"==typeof t.extraOptions.mongocryptdURI||i.getDefaultAutoSelectFamily||(e.family=4),i.getDefaultAutoSelectFamily&&Object.assign(e,(0,h.autoSelectSocketOptions)(this._client.s?.options??{})),this._mongocryptdClient=new d.MongoClient(this._mongocryptdManager.uri,e)}}async init(){if(!this._bypassMongocryptdAndCryptShared&&!this.cryptSharedLibVersionInfo){if(!this._mongocryptdManager)throw new l.MongoRuntimeError("Reached impossible state: mongocryptdManager is undefined when neither bypassSpawn nor the shared lib are specified.");if(!this._mongocryptdClient)throw new l.MongoRuntimeError("Reached impossible state: mongocryptdClient is undefined when neither bypassSpawn nor the shared lib are specified.");this._mongocryptdManager.bypassSpawn||await this._mongocryptdManager.spawn();try{return await this._mongocryptdClient.connect()}catch(e){throw new l.MongoRuntimeError("Unable to connect to `mongocryptd`, please make sure it is running or in your PATH for auto-spawn",{cause:e})}}}async close(){await(this._mongocryptdClient?.close())}async encrypt(e,t,o={}){if(o.signal?.throwIfAborted(),this._bypassEncryption)return t;const n=r.isBuffer(t)?t:(0,s.serialize)(t,o),i=this._mongocrypt.makeEncryptionContext(u.MongoDBCollectionNamespace.fromString(e).db,n);i.id=this._contextCounter++,i.ns=e,i.document=t;const a=new f.StateMachine({promoteValues:!1,promoteLongs:!1,proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:(0,h.autoSelectSocketOptions)(this._client.s.options)});return(0,s.deserialize)(await a.execute(this,i,o),{promoteValues:!1,promoteLongs:!1})}async decrypt(e,t={}){t.signal?.throwIfAborted();const o=this._mongocrypt.makeDecryptionContext(e);o.id=this._contextCounter++;const n=new f.StateMachine({...t,proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:(0,h.autoSelectSocketOptions)(this._client.s.options)});return await n.execute(this,o,t)}async askForKMSCredentials(){return await(0,g.refreshKMSCredentials)(this._kmsProviders,this._credentialProviders)}get cryptSharedLibVersionInfo(){return this._mongocrypt.cryptSharedLibVersionInfo}static get libmongocryptVersion(){return S.getMongoCrypt().libmongocryptVersion}}t.AutoEncrypter=S},9405:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RunCursorCommandOperation=t.RunCommandOperation=void 0;const n=o(72216),r=o(28947);class i extends r.AbstractOperation{constructor(e,t,o){super(o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.command=t,this.options=o,this.ns=e.withCollection("$cmd")}get commandName(){return"runCommand"}buildCommand(e,t){return this.command}buildOptions(e){return{...this.options,session:this.session,timeoutContext:e,signal:this.options.signal,readPreference:this.options.readPreference}}}t.RunCommandOperation=i,t.RunCursorCommandOperation=class extends i{constructor(){super(...arguments),this.SERVER_COMMAND_RESPONSE_TYPE=n.CursorResponse}handleOk(e){return e}}},10176:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListIndexesCursor=void 0;const n=o(39131),r=o(15002),i=o(40927);class s extends i.AbstractCursor{constructor(e,t){super(e.client,e.s.namespace,t),this.parent=e,this.options=t}clone(){return new s(this.parent,{...this.options,...this.cursorOptions})}async _initialize(e){const t=new r.ListIndexesOperation(this.parent,{...this.cursorOptions,...this.options,session:e}),o=await(0,n.executeOperation)(this.parent.client,t,this.timeoutContext);return{server:t.server,session:e,response:o}}}t.ListIndexesCursor=s},10187:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mapCliToDriver=f;const n=o(92762),r=o(42344);function i(e,t,o){return{...e,driverOptions:{...e.driverOptions,[t]:o}}}function s(e,t,o){const n=e.driverOptions.serverApi,r="string"==typeof n?{version:n}:{...n};return r[t]=o,i(e,"serverApi",r)}function a(e,t,o){const n=e.driverOptions.autoEncryption??{};return n[t]=o,i(e,"autoEncryption",n)}function c(e,t,o){const n=e.driverOptions.autoEncryption?.extraOptions??{};return n[t]=o,a(e,"extraOptions",n)}function l(e,t,o){const{kmsProviders:n}=e.driverOptions.autoEncryption??{},r=n?.aws??{};return r[t]=o,a(e,"kmsProviders",{...n,aws:r})}function d(e,t,o){const n=new r.ConnectionString(e.connectionString,{looseValidation:!0}),i=n.typedSearchParams();return""===o||void 0===o?i.delete(t):i.set(t,o),{...e,connectionString:n.toString()}}function u(e,t,o){const n=new r.ConnectionString(e.connectionString,{looseValidation:!0});return n[t]=o,{...e,connectionString:n.toString()}}function h(e,t,o){const n=new r.ConnectionString(e.connectionString,{looseValidation:!0}),i=new r.CommaAndColonSeparatedRecord(n.typedSearchParams().get("authMechanismProperties"));return""===o||void 0===o?i.delete(t):i.set(t,o),d(e,"authMechanismProperties",i)}function m(e,t,o){return i(e,"oidc",{...e.driverOptions.oidc,[t]:o})}const p={apiDeprecationErrors:(e,t)=>s(e,"deprecationErrors",t),apiStrict:(e,t)=>s(e,"strict",t),apiVersion:(e,t)=>s(e,"version",t),awsAccessKeyId:(e,t)=>l(e,"accessKeyId",t),awsSecretAccessKey:(e,t)=>l(e,"secretAccessKey",t),awsSessionToken:(e,t)=>l(e,"sessionToken",t),awsIamSessionToken:(e,t)=>h(e,"AWS_SESSION_TOKEN",t),csfleLibraryPath:(e,t)=>c(e,"cryptSharedLibPath",t),cryptSharedLibPath:(e,t)=>c(e,"cryptSharedLibPath",t),gssapiServiceName:(e,t)=>h(e,"SERVICE_NAME",t),sspiRealmOverride:(e,t)=>h(e,"SERVICE_REALM",t),sspiHostnameCanonicalization:(e,t)=>h(e,"CANONICALIZE_HOST_NAME",function(e){if(""!==e)return"true"===e||"false"===e?"true"===e:e}(t)),authenticationDatabase:(e,t)=>d(e,"authSource",t),authenticationMechanism:(e,t)=>d(e,"authMechanism",t),keyVaultNamespace:(e,t)=>a(e,"keyVaultNamespace",t),password:(e,t)=>u(e,"password",encodeURIComponent(t)),retryWrites:(e,t)=>d(e,"retryWrites",t),tls:(e,t)=>d(e,"tls",t),tlsAllowInvalidCertificates:(e,t)=>d(e,"tlsAllowInvalidCertificates",t),tlsAllowInvalidHostnames:(e,t)=>d(e,"tlsAllowInvalidHostnames",t),tlsCAFile:(e,t)=>d(e,"tlsCAFile",t),tlsCRLFile:(e,t)=>d(e,"tlsCRLFile",t),tlsCertificateKeyFile:(e,t)=>d(e,"tlsCertificateKeyFile",t),tlsCertificateKeyFilePassword:(e,t)=>d(e,"tlsCertificateKeyFilePassword",t),username:(e,t)=>u(e,"username",encodeURIComponent(t)),oidcRedirectUri:(e,t)=>m(e,"redirectURI",t),oidcTrustedEndpoint:(e,t)=>function(e,t,o){return i(e,"authMechanismProperties",{...e.driverOptions.authMechanismProperties,[t]:o})}(e,"ALLOWED_HOSTS",t?function(e){const t=new r.ConnectionString(e.connectionString,{looseValidation:!0}),o=t.hosts.map((e=>{const{host:o}=e.match(/^(?<host>.+?)(?<port>:[^:\]\[]+)?$/)?.groups;if(o.startsWith("[")&&o.endsWith("]"))return o.slice(1,-1);if(/^[0-9.]+$/.exec(o))return o;if(!o.includes(".")||!t.isSRV)return o;const n=o.split(".");return n[0]="*",n.join(".")}));return[...new Set(o)]}(e):void 0),oidcFlows:(e,t)=>m(e,"allowedFlows",t.split(",").filter(Boolean)),oidcIdTokenAsAccessToken:(e,t)=>m(e,"passIdTokenAsAccessToken",t),oidcNoNonce:(e,t)=>m(e,"skipNonceInAuthCodeRequest",t),browser:(e,t)=>m(e,"openBrowser","string"==typeof t?{command:t}:t)};function g(e,t,o){return p[t]?.(e,o)??e}function f(e,t){for(const o of Object.keys(e)){const n=e[o];null!=n&&""!==n&&(t=g(t,o,n))}return function(e,t){if(!e.connectionString)return;const o=new r.ConnectionString(e.connectionString,{looseValidation:!0});if(o.password&&!o.username){let e="Invalid connection information: Password specified but no username provided";throw t.password&&!t.port&&(e+=" (did you mean '--port' instead of '-p'?)"),new n.MongoshInvalidInputError(e,n.CommonErrors.InvalidArgument)}new r.ConnectionString(e.connectionString,{looseValidation:!1})}(t,e),t}t.default=f},11280:(e,t,o)=>{var n=o(21655).URL;Object.defineProperty(t,"__esModule",{value:!0}),t.callback=void 0;const r=o(43975),i=o(36997),s=o(30306),a=Object.freeze({Metadata:"true",Accept:"application/json"});t.callback=async e=>{const t=e.tokenAudience,o=e.username;if(!t)throw new i.MongoAzureError("TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is azure.");const c=await async function(e,t){const o=new n(r.AZURE_BASE_URL);(0,r.addAzureParams)(o,e,t);const c=await(0,s.get)(o,{headers:a});if(200!==c.status)throw new i.MongoAzureError(`Status code ${c.status} returned from the Azure endpoint. Response body: ${c.body}`);const l=JSON.parse(c.body);return{accessToken:l.access_token,expiresInSeconds:Number(l.expires_in)}}(t,o);if(null==(l=c)||"object"!=typeof l||!("accessToken"in l)||"string"!=typeof l.accessToken||!("expiresInSeconds"in l)||"number"!=typeof l.expiresInSeconds)throw new i.MongoAzureError("Azure endpoint did not return a value with only access_token and expires_in properties");var l;return c}},11337:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InsertOneOperation=t.InsertOperation=void 0;const n=o(72216),r=o(36997),i=o(30306),s=o(41539),a=o(28947);class c extends s.CommandOperation{constructor(e,t,o){super(void 0,o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options={...o,checkKeys:o.checkKeys??!1},this.ns=e,this.documents=t}get commandName(){return"insert"}buildCommandDocument(e,t){const o=this.options??{},n="boolean"!=typeof o.ordered||o.ordered,r={insert:this.ns.collection,documents:this.documents,ordered:n};return"boolean"==typeof o.bypassDocumentValidation&&(r.bypassDocumentValidation=o.bypassDocumentValidation),void 0!==o.comment&&(r.comment=o.comment),r}}t.InsertOperation=c;class l extends c{constructor(e,t,o){super(e.s.namespace,[(0,i.maybeAddIdToDocuments)(e,t,o)],o)}handleOk(e){const t=super.handleOk(e);if(t.code)throw new r.MongoServerError(t);if(t.writeErrors)throw new r.MongoServerError(t.writeErrors[0]);return{acknowledged:0!==this.writeConcern?.w,insertedId:this.documents[0]._id}}}t.InsertOneOperation=l,(0,a.defineAspects)(c,[a.Aspect.RETRYABLE,a.Aspect.WRITE_OPERATION,a.Aspect.SUPPORTS_RAW_DATA]),(0,a.defineAspects)(l,[a.Aspect.RETRYABLE,a.Aspect.WRITE_OPERATION,a.Aspect.SUPPORTS_RAW_DATA])},12668:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FindCursor=t.FLAGS=void 0;const n=o(72216),r=o(36997),i=o(27272),s=o(85673),a=o(39131),c=o(25859),l=o(24007),d=o(30306),u=o(44058);t.FLAGS=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"];class h extends u.ExplainableCursor{constructor(e,t,o={},n={}){super(e,t,n),this.numReturned=0,this.cursorFilter=o,this.findOptions=n,null!=n.sort&&(this.findOptions.sort=(0,l.formatSort)(n.sort))}clone(){const e=(0,d.mergeOptions)({},this.findOptions);return delete e.session,new h(this.client,this.namespace,this.cursorFilter,{...e})}map(e){return super.map(e)}async _initialize(e){const t={...this.findOptions,...this.cursorOptions,session:e,signal:this.signal};if(t.explain)try{(0,i.validateExplainTimeoutOptions)(t,i.Explain.fromOptions(t))}catch{throw new r.MongoAPIError("timeoutMS cannot be used with explain when explain is specified in findOptions")}const o=new c.FindOperation(this.namespace,this.cursorFilter,t),n=await(0,a.executeOperation)(this.client,o,this.timeoutContext);return this.numReturned=n.batchSize,{server:o.server,session:e,response:n}}async getMore(){const e=this.numReturned,t=this.findOptions.limit??1/0,o=t-e;if(e===t&&!this.id?.isZero()){try{await this.close()}catch(e){(0,d.squashError)(e)}return n.CursorResponse.emptyGetMore}let r=d.noop;const{batchSize:i}=this.cursorOptions;null!=i&&i>o&&(this.cursorOptions.batchSize=o,r=()=>{this.cursorOptions.batchSize=i});try{const e=await super.getMore();return this.numReturned=this.numReturned+e.batchSize,e}finally{r?.()}}async count(e){if((0,d.emitWarningOnce)("cursor.count is deprecated and will be removed in the next major version, please use `collection.estimatedDocumentCount` or `collection.countDocuments` instead "),"boolean"==typeof e)throw new r.MongoInvalidArgumentError("Invalid first parameter to count");return await(0,a.executeOperation)(this.client,new s.CountOperation(this.namespace,this.cursorFilter,{...this.findOptions,...this.cursorOptions,...e}))}async explain(e,t){const{explain:o,timeout:n}=this.resolveExplainTimeoutOptions(e,t);return(await(0,a.executeOperation)(this.client,new c.FindOperation(this.namespace,this.cursorFilter,{...this.findOptions,...this.cursorOptions,...n,explain:o??!0}))).shift(this.deserializationOptions)}filter(e){return this.throwIfInitialized(),this.cursorFilter=e,this}hint(e){return this.throwIfInitialized(),this.findOptions.hint=e,this}min(e){return this.throwIfInitialized(),this.findOptions.min=e,this}max(e){return this.throwIfInitialized(),this.findOptions.max=e,this}returnKey(e){return this.throwIfInitialized(),this.findOptions.returnKey=e,this}showRecordId(e){return this.throwIfInitialized(),this.findOptions.showRecordId=e,this}addQueryModifier(e,t){if(this.throwIfInitialized(),"$"!==e[0])throw new r.MongoInvalidArgumentError(`${e} is not a valid query modifier`);switch(e.substr(1)){case"comment":this.findOptions.comment=t;break;case"explain":this.findOptions.explain=t;break;case"hint":this.findOptions.hint=t;break;case"max":this.findOptions.max=t;break;case"maxTimeMS":this.findOptions.maxTimeMS=t;break;case"min":this.findOptions.min=t;break;case"orderby":this.findOptions.sort=(0,l.formatSort)(t);break;case"query":this.cursorFilter=t;break;case"returnKey":this.findOptions.returnKey=t;break;case"showDiskLoc":this.findOptions.showRecordId=t;break;default:throw new r.MongoInvalidArgumentError(`Invalid query modifier: ${e}`)}return this}comment(e){return this.throwIfInitialized(),this.findOptions.comment=e,this}maxAwaitTimeMS(e){if(this.throwIfInitialized(),"number"!=typeof e)throw new r.MongoInvalidArgumentError("Argument for maxAwaitTimeMS must be a number");return this.findOptions.maxAwaitTimeMS=e,this}maxTimeMS(e){if(this.throwIfInitialized(),"number"!=typeof e)throw new r.MongoInvalidArgumentError("Argument for maxTimeMS must be a number");return this.findOptions.maxTimeMS=e,this}project(e){return this.throwIfInitialized(),this.findOptions.projection=e,this}sort(e,t){if(this.throwIfInitialized(),this.findOptions.tailable)throw new r.MongoTailableCursorError("Tailable cursor does not support sorting");return this.findOptions.sort=(0,l.formatSort)(e,t),this}allowDiskUse(e=!0){if(this.throwIfInitialized(),!this.findOptions.sort)throw new r.MongoInvalidArgumentError('Option "allowDiskUse" requires a sort specification');return e?(this.findOptions.allowDiskUse=!0,this):(this.findOptions.allowDiskUse=!1,this)}collation(e){return this.throwIfInitialized(),this.findOptions.collation=e,this}limit(e){if(this.throwIfInitialized(),this.findOptions.tailable)throw new r.MongoTailableCursorError("Tailable cursor does not support limit");if("number"!=typeof e)throw new r.MongoInvalidArgumentError('Operation "limit" requires an integer');return this.findOptions.limit=e,this}skip(e){if(this.throwIfInitialized(),this.findOptions.tailable)throw new r.MongoTailableCursorError("Tailable cursor does not support skip");if("number"!=typeof e)throw new r.MongoInvalidArgumentError('Operation "skip" requires an integer');return this.findOptions.skip=e,this}}t.FindCursor=h},13237:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregationCursor=void 0;const n=o(36997),r=o(27272),i=o(86065),s=o(39131),a=o(30306),c=o(40927),l=o(44058);class d extends l.ExplainableCursor{constructor(e,t,o=[],r={}){super(e,t,r),this.pipeline=o,this.aggregateOptions=r;const i=this.pipeline[this.pipeline.length-1];if(null!=this.cursorOptions.timeoutMS&&this.cursorOptions.timeoutMode===c.CursorTimeoutMode.ITERATION&&(null!=i?.$merge||null!=i?.$out))throw new n.MongoAPIError("Cannot use $out or $merge stage with ITERATION timeoutMode")}clone(){const e=(0,a.mergeOptions)({},this.aggregateOptions);return delete e.session,new d(this.client,this.namespace,this.pipeline,{...e})}map(e){return super.map(e)}async _initialize(e){const t={...this.aggregateOptions,...this.cursorOptions,session:e,signal:this.signal};if(t.explain)try{(0,r.validateExplainTimeoutOptions)(t,r.Explain.fromOptions(t))}catch{throw new n.MongoAPIError("timeoutMS cannot be used with explain when explain is specified in aggregateOptions")}const o=new i.AggregateOperation(this.namespace,this.pipeline,t),a=await(0,s.executeOperation)(this.client,o,this.timeoutContext);return{server:o.server,session:e,response:a}}async explain(e,t){const{explain:o,timeout:n}=this.resolveExplainTimeoutOptions(e,t);return(await(0,s.executeOperation)(this.client,new i.AggregateOperation(this.namespace,this.pipeline,{...this.aggregateOptions,...this.cursorOptions,...n,explain:o??!0}))).shift(this.deserializationOptions)}addStage(e){if(this.throwIfInitialized(),null!=this.cursorOptions.timeoutMS&&this.cursorOptions.timeoutMode===c.CursorTimeoutMode.ITERATION&&(null!=e.$out||null!=e.$merge))throw new n.MongoAPIError("Cannot use $out or $merge stage with ITERATION timeoutMode");return this.pipeline.push(e),this}group(e){return this.addStage({$group:e})}limit(e){return this.addStage({$limit:e})}match(e){return this.addStage({$match:e})}out(e){return this.addStage({$out:e})}project(e){return this.addStage({$project:e})}lookup(e){return this.addStage({$lookup:e})}redact(e){return this.addStage({$redact:e})}skip(e){return this.addStage({$skip:e})}sort(e){return this.addStage({$sort:e})}unwind(e){return this.addStage({$unwind:e})}geoNear(e){return this.addStage({$geoNear:e})}}t.AggregationCursor=d},15002:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListIndexesOperation=t.DropIndexOperation=t.CreateIndexesOperation=void 0;const n=o(72216),r=o(36997),i=o(30306),s=o(41539),a=o(28947),c=new Set(["background","unique","name","partialFilterExpression","sparse","hidden","expireAfterSeconds","storageEngine","collation","version","weights","default_language","language_override","textIndexVersion","2dsphereIndexVersion","bits","min","max","bucketSize","wildcardProjection"]);class l extends s.CommandOperation{constructor(e,t,o,r){super(e,r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=r??{},this.options.collation=void 0,this.collectionName=t,this.indexes=o.map((e=>{const t=e.key instanceof Map?e.key:new Map(Object.entries(e.key)),o=e.name??Array.from(t).flat().join("_"),n=function(e){const t=Object.entries(e).filter((([e])=>c.has(e)));return Object.fromEntries(t.map((([e,t])=>"version"===e?["v",t]:[e,t])))}(e);return{...n,name:o,key:t}})),this.ns=e.s.namespace}static fromIndexDescriptionArray(e,t,o,n){return new l(e,t,o,n)}static fromIndexSpecification(e,t,o,n={}){const r=function(e){const t=new Map,o=Array.isArray(e)&&(n=e,!Array.isArray(n)||2!==n.length||"number"!=typeof(r=n[1])&&"2d"!==r&&"2dsphere"!==r&&"text"!==r&&"geoHaystack"!==r)?e:[e];var n,r;for(const e of o)if("string"==typeof e)t.set(e,1);else if(Array.isArray(e))t.set(e[0],e[1]??1);else if(e instanceof Map)for(const[o,n]of e)t.set(o,n);else if((0,i.isObject)(e))for(const[o,n]of Object.entries(e))t.set(o,n);return t}(o),s={...n,key:r};return new l(e,t,[s],n)}get commandName(){return"createIndexes"}buildCommandDocument(e){const t=this.options,o=this.indexes,n=(0,i.maxWireVersion)(e),s={createIndexes:this.collectionName,indexes:o};if(null!=t.commitQuorum){if(n<9)throw new r.MongoCompatibilityError("Option `commitQuorum` for `createIndexes` not supported on servers < 4.4");s.commitQuorum=t.commitQuorum}return s}handleOk(e){return this.indexes.map((e=>e.name||""))}}t.CreateIndexesOperation=l;class d extends s.CommandOperation{constructor(e,t,o){super(e,o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=o??{},this.collection=e,this.indexName=t,this.ns=e.fullNamespace}get commandName(){return"dropIndexes"}buildCommandDocument(e){return{dropIndexes:this.collection.collectionName,index:this.indexName}}}t.DropIndexOperation=d;class u extends s.CommandOperation{constructor(e,t){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=n.CursorResponse,this.options={...t},delete this.options.writeConcern,this.collectionNamespace=e.s.namespace}get commandName(){return"listIndexes"}buildCommandDocument(e){const t=(0,i.maxWireVersion)(e),o=this.options.batchSize?{batchSize:this.options.batchSize}:{},n={listIndexes:this.collectionNamespace.collection,cursor:o};return t>=9&&void 0!==this.options.comment&&(n.comment=this.options.comment),n}handleOk(e){return e}}t.ListIndexesOperation=u,(0,a.defineAspects)(u,[a.Aspect.READ_OPERATION,a.Aspect.RETRYABLE,a.Aspect.CURSOR_CREATING,a.Aspect.SUPPORTS_RAW_DATA]),(0,a.defineAspects)(l,[a.Aspect.WRITE_OPERATION,a.Aspect.SUPPORTS_RAW_DATA]),(0,a.defineAspects)(d,[a.Aspect.WRITE_OPERATION,a.Aspect.SUPPORTS_RAW_DATA])},17502:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WaitQueueTimeoutError=t.PoolClearedOnNetworkError=t.PoolClearedError=t.PoolClosedError=void 0;const n=o(36997);class r extends n.MongoDriverError{constructor(e){super("Attempted to check out a connection from closed connection pool"),this.address=e.address}get name(){return"MongoPoolClosedError"}}t.PoolClosedError=r;class i extends n.MongoNetworkError{constructor(e,t){super(t||`Connection pool for ${e.address} was cleared because another operation failed with: "${e.serverError?.message}"`,e.serverError?{cause:e.serverError}:void 0),this.address=e.address,this.addErrorLabel(n.MongoErrorLabel.PoolRequestedRetry)}get name(){return"MongoPoolClearedError"}}t.PoolClearedError=i,t.PoolClearedOnNetworkError=class extends i{constructor(e){super(e,`Connection to ${e.address} interrupted due to server monitor timeout`)}get name(){return"PoolClearedOnNetworkError"}};class s extends n.MongoDriverError{constructor(e,t){super(e),this.address=t}get name(){return"MongoWaitQueueTimeoutError"}}t.WaitQueueTimeoutError=s},17817:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Encrypter=void 0;const n=o(9095),r=o(34842),i=o(98517),s=o(36997),a=o(88757);t.Encrypter=class{constructor(e,t,o){if("object"!=typeof o.autoEncryption)throw new s.MongoInvalidArgumentError('Option "autoEncryption" must be specified');this.internalClient=null,this.bypassAutoEncryption=!!o.autoEncryption.bypassAutoEncryption,this.needsConnecting=!1,0===o.maxPoolSize&&null==o.autoEncryption.keyVaultClient?o.autoEncryption.keyVaultClient=e:null==o.autoEncryption.keyVaultClient&&(o.autoEncryption.keyVaultClient=this.getInternalClient(e,t,o)),this.bypassAutoEncryption?o.autoEncryption.metadataClient=void 0:0===o.maxPoolSize?o.autoEncryption.metadataClient=e:o.autoEncryption.metadataClient=this.getInternalClient(e,t,o),o.proxyHost&&(o.autoEncryption.proxyOptions={proxyHost:o.proxyHost,proxyPort:o.proxyPort,proxyUsername:o.proxyUsername,proxyPassword:o.proxyPassword}),this.autoEncrypter=new n.AutoEncrypter(e,o.autoEncryption)}getInternalClient(e,t,o){let n=this.internalClient;if(null==n){const i={};for(const e of[...Object.getOwnPropertyNames(o),...Object.getOwnPropertySymbols(o)])["autoEncryption","minPoolSize","servers","caseTranslate","dbName"].includes(e)||Reflect.set(i,e,Reflect.get(o,e));i.minPoolSize=0,n=new a.MongoClient(t,i),this.internalClient=n;for(const t of r.MONGO_CLIENT_EVENTS)for(const o of e.listeners(t))n.on(t,o);e.on("newListener",((e,t)=>{n?.on(e,t)})),this.needsConnecting=!0}return n}async connectInternalClient(){const e=this.internalClient;this.needsConnecting&&null!=e&&(this.needsConnecting=!1,await e.connect())}async close(e){let t;try{await this.autoEncrypter.close()}catch(e){t=e}const o=this.internalClient;if(null!=o&&e!==o)return await o.close();if(null!=t)throw t}static checkForMongoCrypt(){const e=(0,i.getMongoDBClientEncryption)();if("kModuleError"in e)throw new s.MongoMissingDependencyError("Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project",{cause:e.kModuleError,dependencyName:"mongodb-client-encryption"})}}},18370:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RunCommandCursor=void 0;const n=o(36997),r=o(39131),i=o(87192),s=o(9405),a=o(30306),c=o(40927);class l extends c.AbstractCursor{setComment(e){return this.getMoreOptions.comment=e,this}setMaxTimeMS(e){return this.getMoreOptions.maxAwaitTimeMS=e,this}setBatchSize(e){return this.getMoreOptions.batchSize=e,this}clone(){throw new n.MongoAPIError("Clone not supported, create a new cursor with db.runCursorCommand")}withReadConcern(e){throw new n.MongoAPIError("RunCommandCursor does not support readConcern it must be attached to the command being run")}addCursorFlag(e,t){throw new n.MongoAPIError("RunCommandCursor does not support cursor flags, they must be attached to the command being run")}maxTimeMS(e){throw new n.MongoAPIError("maxTimeMS must be configured on the command document directly, to configure getMore.maxTimeMS use cursor.setMaxTimeMS()")}batchSize(e){throw new n.MongoAPIError("batchSize must be configured on the command document directly, to configure getMore.batchSize use cursor.setBatchSize()")}constructor(e,t,o={}){super(e.client,(0,a.ns)(e.namespace),o),this.getMoreOptions={},this.db=e,this.command=Object.freeze({...t})}async _initialize(e){const t=new s.RunCursorCommandOperation(this.db.s.namespace,this.command,{...this.cursorOptions,session:e,readPreference:this.cursorOptions.readPreference}),o=await(0,r.executeOperation)(this.client,t,this.timeoutContext);return{server:t.server,session:e,response:o}}async getMore(){if(!this.session)throw new n.MongoRuntimeError("Unexpected null session. A cursor creating command should have set this");const e=new i.GetMoreOperation(this.namespace,this.id,this.server,{...this.cursorOptions,session:this.session,...this.getMoreOptions});return await(0,r.executeOperation)(this.client,e,this.timeoutContext)}}t.RunCommandCursor=l},20552:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HumanCallbackWorkflow=void 0;const n=o(77953),r=o(36997),i=o(33628),s=o(41720),a=o(50558);class c extends a.CallbackWorkflow{constructor(e,t){super(e,t)}async execute(e,t){if(this.cache.hasAccessToken){const o=this.cache.getAccessToken();e.accessToken=o;try{return await this.finishAuthentication(e,t,o)}catch(o){if(o instanceof r.MongoError&&o.code===r.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeAccessToken(),delete e.accessToken,await this.execute(e,t);throw o}}if(this.cache.hasRefreshToken){const o=this.cache.getRefreshToken(),n=await this.fetchAccessToken(this.cache.getIdpInfo(),t,o);this.cache.put(n),e.accessToken=n.accessToken;try{return await this.finishAuthentication(e,t,n.accessToken)}catch(o){if(o instanceof r.MongoError&&o.code===r.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeRefreshToken(),delete e.accessToken,await this.execute(e,t);throw o}}const o=await this.startAuthentication(e,t),i=o.conversationId,s=n.BSON.deserialize(o.payload.buffer),a=await this.fetchAccessToken(s,t);return this.cache.put(a,s),e.accessToken=a.accessToken,await this.finishAuthentication(e,t,a.accessToken,i)}async fetchAccessToken(e,t,o){const n=new AbortController,c={timeoutContext:n.signal,version:s.OIDC_VERSION,idpInfo:e};t.username&&(c.username=t.username),o&&(c.refreshToken=o);const l=i.Timeout.expires(a.HUMAN_TIMEOUT_MS);try{return await Promise.race([this.executeAndValidateCallback(c),l])}catch(e){if(i.TimeoutError.is(e))throw n.abort(),new r.MongoOIDCError(`OIDC callback timed out after ${a.HUMAN_TIMEOUT_MS}ms.`);throw e}finally{l.clear()}}}t.HumanCallbackWorkflow=c},20693:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListDatabasesOperation=void 0;const n=o(72216),r=o(30306),i=o(41539),s=o(28947);class a extends i.CommandOperation{constructor(e,t){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=t??{},this.ns=new r.MongoDBNamespace("admin","$cmd")}get commandName(){return"listDatabases"}buildCommandDocument(e,t){const o={listDatabases:1};return"boolean"==typeof this.options.nameOnly&&(o.nameOnly=this.options.nameOnly),this.options.filter&&(o.filter=this.options.filter),"boolean"==typeof this.options.authorizedDatabases&&(o.authorizedDatabases=this.options.authorizedDatabases),(0,r.maxWireVersion)(e)>=9&&void 0!==this.options.comment&&(o.comment=this.options.comment),o}}t.ListDatabasesOperation=a,(0,s.defineAspects)(a,[s.Aspect.READ_OPERATION,s.Aspect.RETRYABLE])},20753:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.loadAWSCredentials=async function(e,t){const o=new n.AWSSDKCredentialProvider(t),{SecretAccessKey:r="",AccessKeyId:i="",Token:s}=await o.getCredentials(),a={secretAccessKey:r,accessKeyId:i};return null!=s&&(a.sessionToken=s),{...e,aws:a}};const n=o(71260)},21427:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GSSAPI=t.GSSAPICanonicalizationValue=void 0,t.performGSSAPICanonicalizeHostName=m,t.resolveCname=p;const n=o(79498),r=o(87098),i=o(98517),s=o(36997),a=o(30306),c=o(68950);async function l(e,t){return await e.command((0,a.ns)("$external.$cmd"),t)}let d;t.GSSAPICanonicalizationValue=Object.freeze({on:!0,off:!1,none:"none",forward:"forward",forwardAndReverse:"forwardAndReverse"});class u extends c.AuthProvider{async auth(e){const{connection:t,credentials:o}=e;if(null==o)throw new s.MongoMissingCredentialsError("Credentials required for GSSAPI authentication");const{username:n}=o,a=await async function(e){const{hostAddress:t}=e.options,{credentials:o}=e;if(!t||"string"!=typeof t.host||!o)throw new s.MongoInvalidArgumentError("Connection must have host and port and credentials defined.");if(d||(d=(0,i.getKerberos)()),"kModuleError"in d)throw d.kModuleError;const{initializeClient:n}=d,{username:a,password:c}=o,l=o.mechanismProperties,u=l.SERVICE_NAME??"mongodb",h=await m(t.host,l),p={};null!=c&&Object.assign(p,{user:a,password:c});const g=l.SERVICE_HOST??h;let f=`${u}${"win32"===r.platform()?"/":"@"}${g}`;return"SERVICE_REALM"in l&&(f=`${f}@${l.SERVICE_REALM}`),await n(f,p)}(e),c=await a.step(""),u=await l(t,function(e){return{saslStart:1,mechanism:"GSSAPI",payload:e,autoAuthorize:1}}(c)),p=await h(a,10,u.payload),g=await l(t,function(e,t){return{saslContinue:1,conversationId:t,payload:e}}(p,u.conversationId)),f=await async function(e,t,o){const n=await e.unwrap(o);return await e.wrap(n||"",{user:t})}(a,n,g.payload);await l(t,{saslContinue:1,conversationId:g.conversationId,payload:f})}}async function h(e,t,o){try{return await e.step(o)||""}catch(n){if(0===t)throw n;return await h(e,t-1,o)}}async function m(e,o){const r=o.CANONICALIZE_HOST_NAME;if(!r||r===t.GSSAPICanonicalizationValue.none)return e;if(r!==t.GSSAPICanonicalizationValue.on&&r!==t.GSSAPICanonicalizationValue.forwardAndReverse)return await p(e);{const{address:t}=await n.promises.lookup(e);try{const o=await n.promises.resolvePtr(t);return o.length>0?o[0]:e}catch{return await p(e)}}}async function p(e){try{const t=await n.promises.resolveCname(e);return t.length>0?t[0]:e}catch{return e}}t.GSSAPI=u},22643:(e,t,o)=>{var n=o(21655).URL;Object.defineProperty(t,"__esModule",{value:!0}),t.callback=void 0;const r=o(36997),i=o(30306),s=Object.freeze({"Metadata-Flavor":"Google"});t.callback=async e=>{const t=e.tokenAudience;if(!t)throw new r.MongoGCPError("TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is gcp.");return await async function(e){const t=new n("http://metadata/computeMetadata/v1/instance/service-accounts/default/identity");t.searchParams.append("audience",e);const o=await(0,i.get)(t,{headers:s});if(200!==o.status)throw new r.MongoGCPError(`Status code ${o.status} returned from the GCP endpoint. Response body: ${o.body}`);return{accessToken:o.body}}(t)}},23121:(e,t,o)=>{var n=o(34110).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.CryptoConnection=t.SizedMessageTransform=t.Connection=void 0,t.hasSessionSupport=function(e){return null!=e.description.logicalSessionTimeoutMinutes};const r=o(64371),i=o(31713),s=o(77953),a=o(34842),c=o(36997),l=o(60866),d=o(72361),u=o(74891),h=o(90648),m=o(86098),p=o(33628),g=o(30306),f=o(60449),S=o(87535),E=o(62808),y=o(73738),b=o(58514),O=o(72216),C=o(80351);class M extends d.TypedEventEmitter{static{this.COMMAND_STARTED=a.COMMAND_STARTED}static{this.COMMAND_SUCCEEDED=a.COMMAND_SUCCEEDED}static{this.COMMAND_FAILED=a.COMMAND_FAILED}static{this.CLUSTER_TIME_RECEIVED=a.CLUSTER_TIME_RECEIVED}static{this.CLOSE=a.CLOSE}static{this.PINNED=a.PINNED}static{this.UNPINNED=a.UNPINNED}constructor(e,t){super(),this.lastHelloMS=-1,this.helloOk=!1,this.delayedTimeoutId=null,this.closed=!1,this.clusterTime=null,this.error=null,this.dataEvents=null,this.on("error",g.noop),this.socket=e,this.id=t.id,this.address=function(e,t){if(t.proxyHost)return t.hostAddress.toString();const{remoteAddress:o,remotePort:n}=e;return"string"==typeof o&&"number"==typeof n?g.HostAddress.fromHostPort(o,n).toString():(0,g.uuidV4)().toString("hex")}(e,t),this.socketTimeoutMS=t.socketTimeoutMS??0,this.monitorCommands=t.monitorCommands,this.serverApi=t.serverApi,this.mongoLogger=t.mongoLogger,this.established=!1,this.description=new E.StreamDescription(this.address,t),this.generation=t.generation,this.lastUseTime=(0,g.processTimeMS)(),this.messageStream=this.socket.on("error",this.onSocketError.bind(this)).pipe(new T({connection:this})).on("error",this.onTransformError.bind(this)),this.socket.on("close",this.onClose.bind(this)),this.socket.on("timeout",this.onTimeout.bind(this)),this.messageStream.pause()}get hello(){return this.description.hello}set hello(e){this.description.receiveResponse(e),Object.freeze(this.description)}get serviceId(){return this.hello?.serviceId}get loadBalanced(){return this.description.loadBalanced}get idleTime(){return(0,g.calculateDurationInMs)(this.lastUseTime)}get hasSessionSupport(){return null!=this.description.logicalSessionTimeoutMinutes}get supportsOpMsg(){return null!=this.description&&(0,g.maxWireVersion)(this)>=6&&!this.description.__nodejs_mock_server__}get shouldEmitAndLogCommand(){return(this.monitorCommands||this.established&&!this.authContext?.reauthenticating&&this.mongoLogger?.willLog(l.MongoLoggableComponent.COMMAND,l.SeverityLevel.DEBUG))??!1}markAvailable(){this.lastUseTime=(0,g.processTimeMS)()}onSocketError(e){this.onError(new c.MongoNetworkError(e.message,{cause:e}))}onTransformError(e){this.onError(e)}onError(e){this.cleanup(e)}onClose(){const e=`connection ${this.id} to ${this.address} closed`;this.cleanup(new c.MongoNetworkError(e))}onTimeout(){this.delayedTimeoutId=(0,i.setTimeout)((()=>{const e=`connection ${this.id} to ${this.address} timed out`,t=null==this.hello;this.cleanup(new c.MongoNetworkTimeoutError(e,{beforeHandshake:t}))}),1).unref()}destroy(){if(this.closed)return;this.removeAllListeners(M.PINNED),this.removeAllListeners(M.UNPINNED);const e=`connection ${this.id} to ${this.address} closed`;this.cleanup(new c.MongoNetworkError(e))}cleanup(e){this.closed||(this.socket.destroy(),this.error=e,this.dataEvents?.throw(e).then(void 0,g.squashError),this.closed=!0,this.emit(M.CLOSE))}prepareCommand(e,t,o){let n={...t};const r=(0,C.getReadPreference)(o),i=o?.session;let s=this.clusterTime;if(this.serverApi){const{version:e,strict:t,deprecationErrors:o}=this.serverApi;n.apiVersion=e,null!=t&&(n.apiStrict=t),null!=o&&(n.apiDeprecationErrors=o)}if(this.hasSessionSupport&&i){i.clusterTime&&s&&i.clusterTime.clusterTime.greaterThan(s.clusterTime)&&(s=i.clusterTime);const e=(0,m.applySession)(i,n,o);if(e)throw e}else if(i?.explicit)throw new c.MongoCompatibilityError("Current topology does not support sessions");s&&(n.$clusterTime=s),this.description.type!==h.ServerType.Standalone&&((0,C.isSharded)(this)||this.description.loadBalanced||!this.supportsOpMsg||!0!==o.directConnection||"primary"!==r?.mode?(0,C.isSharded)(this)&&!this.supportsOpMsg&&"primary"!==r?.mode?n={$query:n,$readPreference:r.toJSON()}:"primary"!==r?.mode&&(n.$readPreference=r.toJSON()):n.$readPreference=u.ReadPreference.primaryPreferred.toJSON());const a={numberToSkip:0,numberToReturn:-1,checkKeys:!1,secondaryOk:r.secondaryOk(),...o};return o.timeoutContext?.addMaxTimeMSToCommand(n,o),this.supportsOpMsg?new S.OpMsgRequest(e,n,a):new S.OpQueryRequest(e,n,a)}async*sendWire(e,t,o){this.throwIfAborted();const n=t.socketTimeoutMS??t?.timeoutContext?.getSocketTimeoutMS()??this.socketTimeoutMS;this.socket.setTimeout(n);try{if(await this.writeCommand(e,{agreedCompressor:this.description.compressor??"none",zlibCompressionLevel:this.description.zlibCompressionLevel,timeoutContext:t.timeoutContext,signal:t.signal}),e.moreToCome)return void(yield O.MongoDBResponse.empty);if(this.throwIfAborted(),t.timeoutContext?.csotEnabled()&&null!=t.timeoutContext.minRoundTripTime&&t.timeoutContext.remainingTimeMS<t.timeoutContext.minRoundTripTime)throw new c.MongoOperationTimeoutError("Server roundtrip time is greater than the time remaining");for await(const e of this.readMany(t)){this.socket.setTimeout(0);const t=e.parse(),r=(o??O.MongoDBResponse).make(t);yield r,this.throwIfAborted(),this.socket.setTimeout(n)}}finally{this.socket.setTimeout(0)}}async*sendCommand(e,t,o,n){o?.signal?.throwIfAborted();const r=this.prepareCommand(e.db,t,o);let i=0;this.shouldEmitAndLogCommand&&(i=(0,g.processTimeMS)(),this.emitAndLogCommand(this.monitorCommands,M.COMMAND_STARTED,r.databaseName,this.established,new f.CommandStartedEvent(this,r,this.description.serverConnectionId)));const s=null!=o.documentsReturnedIn&&o.raw?{...o,raw:!1,fieldsAsRaw:{[o.documentsReturnedIn]:!0}}:o;let a,l;try{for await(a of(this.throwIfAborted(),this.sendWire(r,o,n))){if(l=void 0,null!=o.session&&(0,m.updateSessionFromResponse)(o.session,a),a.$clusterTime&&(this.clusterTime=a.$clusterTime,this.emit(M.CLUSTER_TIME_RECEIVED,a.$clusterTime)),0===a.ok){if(o.timeoutContext?.csotEnabled()&&a.isMaxTimeExpiredError)throw new c.MongoOperationTimeoutError("Server reported a timeout error",{cause:new c.MongoServerError(l??=a.toObject(s))});throw new c.MongoServerError(l??=a.toObject(s))}this.shouldEmitAndLogCommand&&this.emitAndLogCommand(this.monitorCommands,M.COMMAND_SUCCEEDED,r.databaseName,this.established,new f.CommandSucceededEvent(this,r,r.moreToCome?{ok:1}:l??=a.toObject(s),i,this.description.serverConnectionId)),null==n?yield l??=a.toObject(s):yield a,this.throwIfAborted()}}catch(e){throw this.shouldEmitAndLogCommand&&this.emitAndLogCommand(this.monitorCommands,M.COMMAND_FAILED,r.databaseName,this.established,new f.CommandFailedEvent(this,r,e,i,this.description.serverConnectionId)),e}}async command(e,t,o={},n){this.throwIfAborted(),o.signal?.throwIfAborted();for await(const r of this.sendCommand(e,t,o,n)){if(o.timeoutContext?.csotEnabled())if(O.MongoDBResponse.is(r)){if(r.isMaxTimeExpiredError)throw new c.MongoOperationTimeoutError("Server reported a timeout error",{cause:new c.MongoServerError(r.toObject())})}else if(Array.isArray(r?.writeErrors)&&r.writeErrors.some((e=>e?.code===c.MONGODB_ERROR_CODES.MaxTimeMSExpired))||r?.writeConcernError?.code===c.MONGODB_ERROR_CODES.MaxTimeMSExpired)throw new c.MongoOperationTimeoutError("Server reported a timeout error",{cause:new c.MongoServerError(r)});return r}throw new c.MongoUnexpectedServerResponseError("Unable to get response from server")}exhaustCommand(e,t,o,n){(async()=>{this.throwIfAborted();for await(const r of this.sendCommand(e,t,o))n(void 0,r),this.throwIfAborted();throw new c.MongoUnexpectedServerResponseError("Server ended moreToCome unexpectedly")})().then(void 0,n)}throwIfAborted(){if(this.error)throw this.error}async writeCommand(e,t){const o="none"!==t.agreedCompressor&&S.OpCompressedRequest.canCompress(e)?new S.OpCompressedRequest(e,{agreedCompressor:t.agreedCompressor??"none",zlibCompressionLevel:t.zlibCompressionLevel??0}):e,r=n.concat(await o.toBin());if(t.timeoutContext?.csotEnabled()&&null!=t.timeoutContext.minRoundTripTime&&t.timeoutContext.remainingTimeMS<t.timeoutContext.minRoundTripTime)throw new c.MongoOperationTimeoutError("Server roundtrip time is greater than the time remaining");try{if(this.socket.write(r))return}catch(e){const t=new c.MongoNetworkError("unexpected error writing to socket",{cause:e});throw this.onError(t),t}const i=(0,g.once)(this.socket,"drain",t),s=t?.timeoutContext?.timeoutForSocketWrite,a=s?Promise.race([i,s]):i;try{return await a}catch(e){if(p.TimeoutError.is(e)){const e=new c.MongoOperationTimeoutError("Timed out at socket write");throw this.onError(e),e}throw e===t.signal?.reason&&this.onError(e),e}finally{s?.clear()}}async*readMany(e){try{this.dataEvents=(0,b.onData)(this.messageStream,e),this.messageStream.resume();for await(const e of this.dataEvents){const t=await(0,y.decompressResponse)(e);if(yield t,!t.moreToCome)return}}catch(t){if(p.TimeoutError.is(t)){const e=new c.MongoOperationTimeoutError(`Timed out during socket read (${t.duration}ms)`);throw this.dataEvents=null,this.onError(e),e}throw t===e.signal?.reason&&this.onError(t),t}finally{this.dataEvents=null,this.messageStream.pause()}}}t.Connection=M;class T extends r.Transform{constructor({connection:e}){super({writableObjectMode:!1,readableObjectMode:!0}),this.bufferPool=new g.BufferPool,this.connection=e}_transform(e,t,o){for(null!=this.connection.delayedTimeoutId&&((0,i.clearTimeout)(this.connection.delayedTimeoutId),this.connection.delayedTimeoutId=null),this.bufferPool.append(e);this.bufferPool.length;){const e=this.bufferPool.getInt32();if(null==e)break;if(e<0)return o(new c.MongoParseError(`Message size cannot be negative: ${e}`));if(e>this.bufferPool.length)break;const t=this.bufferPool.read(e);if(!this.push(t))return o(new c.MongoRuntimeError("SizedMessageTransform does not support backpressure"))}o()}}t.SizedMessageTransform=T,t.CryptoConnection=class extends M{constructor(e,t){super(e,t),this.autoEncrypter=t.autoEncrypter}async command(e,t,o,n){const{autoEncrypter:r}=this;if(!r)throw new c.MongoRuntimeError("No AutoEncrypter available for encryption");if(0===(0,g.maxWireVersion)(this))return await super.command(e,t,o,n);const i=t.find||t.findAndModify?t.sort:null,l=t.createIndexes?t.indexes.map((e=>e.key)):null,d=await r.encrypt(e.toString(),t,o);if(null!=i&&(t.find||t.findAndModify)&&(d.sort=i),null!=l&&t.createIndexes)for(const[e,t]of l.entries())d.indexes[e].key=t;const u=await super.command(e,d,o,n??O.MongoDBResponse),h=await r.decrypt(u.toBytes(),o),m=n?.make(h)??(0,s.deserialize)(h,o);return r[a.kDecorateResult]&&(null==n?(0,g.decorateDecryptionResult)(m,u.toObject(),!0):m instanceof O.CursorResponse&&(m.encryptedResponse=u)),m}}},23942:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EstimatedDocumentCountOperation=void 0;const n=o(72216),r=o(41539),i=o(28947);class s extends r.CommandOperation{constructor(e,t={}){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=t,this.collectionName=e.collectionName}get commandName(){return"count"}buildCommandDocument(e,t){const o={count:this.collectionName};return"number"==typeof this.options.maxTimeMS&&(o.maxTimeMS=this.options.maxTimeMS),void 0!==this.options.comment&&(o.comment=this.options.comment),o}handleOk(e){return e.getNumber("n")??0}}t.EstimatedDocumentCountOperation=s,(0,i.defineAspects)(s,[i.Aspect.READ_OPERATION,i.Aspect.RETRYABLE,i.Aspect.CURSOR_CREATING,i.Aspect.SUPPORTS_RAW_DATA])},24007:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.formatSort=function(e,t){if(null!=e){if("string"==typeof e)return new Map([[e,r(t)]]);if("object"!=typeof e)throw new n.MongoInvalidArgumentError(`Invalid sort format: ${JSON.stringify(e)} Sort must be a valid object`);return i=e,Array.isArray(i)?e.length?function(e){return Array.isArray(e)&&Array.isArray(e[0])}(e)?function(e){const t=e.map((([e,t])=>[`${e}`,r(t)]));return new Map(t)}(e):function(e){if(Array.isArray(e)&&2===e.length)try{return r(e[1]),!0}catch{return!1}return!1}(e)?(s=e,new Map([[`${s[0]}`,r([s[1]])]])):function(e){const t=e.map((e=>[`${e}`,1]));return new Map(t)}(e):void 0:(o=e)instanceof Map&&o.size>0?function(e){const t=Array.from(e).map((([e,t])=>[`${e}`,r(t)]));return new Map(t)}(e):Object.keys(e).length?function(e){const t=Object.entries(e).map((([e,t])=>[`${e}`,r(t)]));return new Map(t)}(e):void 0;var o,i,s}};const n=o(36997);function r(e=1){const t=`${e}`.toLowerCase();if("object"==typeof(o=e)&&null!=o&&"$meta"in o&&"string"==typeof o.$meta)return e;var o;switch(t){case"ascending":case"asc":case"1":return 1;case"descending":case"desc":case"-1":return-1;default:throw new n.MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(e)}`)}}},24968:function(e,t,o){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CliOptionsSchema=t.UnsupportedCliOptions=t.DeprecatedCliOptions=t.CurrentCliOptionsSchema=void 0,t.processPositionalCliOptions=function({parsed:e,positional:t}){const o={...e};var n;return"string"==typeof t[0]&&(o.nodb||"string"!=typeof(n=t[0])||!n.startsWith("mongodb://")&&!n.startsWith("mongodb+srv://")&&(n.endsWith(".js")||n.endsWith(".mongodb"))||(o.connectionSpecifier=t.shift())),o.fileNames=[...o.file??[],...t],o},t.validateCliOptions=function(e){if(!t.CliOptionsSchema.shape.json.safeParse(e.json).success)throw new s.MongoshUnimplementedError("--json can only have the values relaxed, canonical",s.CommonErrors.InvalidArgument);if(!t.CliOptionsSchema.shape.oidcDumpTokens.safeParse(e.oidcDumpTokens).success)throw new s.MongoshUnimplementedError("--oidcDumpTokens can only have the values redacted, include-secrets",s.CommonErrors.InvalidArgument);if(!t.CliOptionsSchema.shape.jsContext.safeParse(e.jsContext).success)throw new s.MongoshUnimplementedError("--jsContext can only have the values repl, plain-vm, auto",s.CommonErrors.InvalidArgument);if(!t.CliOptionsSchema.shape.browser.safeParse(e.browser).success)throw new s.MongoshUnimplementedError("--browser can only be true or a string",s.CommonErrors.InvalidArgument)};const r=n(o(99539)),i=o(3803),s=o(92762);t.CurrentCliOptionsSchema=r.default.object({apiVersion:r.default.string().optional(),authenticationDatabase:r.default.string().optional(),authenticationMechanism:r.default.string().optional(),awsAccessKeyId:r.default.string().optional(),awsIamSessionToken:r.default.string().optional(),awsSecretAccessKey:r.default.string().optional(),awsSessionToken:r.default.string().optional(),csfleLibraryPath:r.default.string().optional(),cryptSharedLibPath:r.default.string().optional(),deepInspect:r.default.boolean().default(!0).optional(),db:r.default.string().optional(),gssapiServiceName:r.default.string().optional(),sspiHostnameCanonicalization:r.default.string().optional(),sspiRealmOverride:r.default.string().optional(),jsContext:r.default.enum(["repl","plain-vm","auto"]).optional(),host:r.default.string().optional(),keyVaultNamespace:r.default.string().optional(),kmsURL:r.default.string().optional(),locale:r.default.string().optional(),oidcFlows:r.default.string().optional(),oidcRedirectUri:r.default.string().optional().register(i.argMetadata,{alias:["oidcRedirectUrl"]}),password:r.default.string().optional().register(i.argMetadata,{alias:["p"]}),port:r.default.string().optional(),username:r.default.string().optional().register(i.argMetadata,{alias:["u"]}),tlsCAFile:r.default.string().optional(),tlsCertificateKeyFile:r.default.string().optional(),tlsCertificateKeyFilePassword:r.default.string().optional(),tlsCertificateSelector:r.default.string().optional(),tlsCRLFile:r.default.string().optional(),tlsDisabledProtocols:r.default.string().optional(),apiDeprecationErrors:r.default.boolean().optional(),apiStrict:r.default.boolean().optional(),buildInfo:r.default.boolean().optional().register(i.argMetadata,{alias:["build-info"]}),exposeAsyncRewriter:r.default.boolean().optional(),help:r.default.boolean().optional().register(i.argMetadata,{alias:["h"]}),ipv6:r.default.boolean().optional(),nodb:r.default.boolean().optional(),norc:r.default.boolean().optional(),oidcTrustedEndpoint:r.default.boolean().optional(),oidcIdTokenAsAccessToken:r.default.boolean().optional().register(i.argMetadata,{alias:["oidcIDTokenAsAccessToken"]}),oidcNoNonce:r.default.boolean().optional(),quiet:r.default.boolean().optional(),retryWrites:r.default.boolean().optional(),shell:r.default.boolean().optional(),skipStartupWarnings:r.default.boolean().optional(),verbose:r.default.boolean().optional(),version:r.default.boolean().optional(),smokeTests:r.default.boolean().optional(),perfTests:r.default.boolean().optional(),tls:r.default.boolean().optional(),tlsAllowInvalidCertificates:r.default.boolean().optional(),tlsAllowInvalidHostnames:r.default.boolean().optional(),tlsFIPSMode:r.default.boolean().optional(),tlsUseSystemCA:r.default.boolean().optional(),eval:r.default.array(r.default.string()).optional(),file:r.default.array(r.default.string()).optional().register(i.argMetadata,{alias:["f"]}),json:r.default.union([r.default.boolean(),r.default.enum(["relaxed","canonical"])]).optional(),oidcDumpTokens:r.default.union([r.default.boolean(),r.default.enum(["redacted","include-secrets"])]).optional(),browser:r.default.union([r.default.literal(!1),r.default.string()]).optional()}),t.DeprecatedCliOptions=r.default.object({ssl:r.default.boolean().optional().register(i.argMetadata,{deprecationReplacement:"tls"}),sslAllowInvalidCertificates:r.default.boolean().optional().register(i.argMetadata,{deprecationReplacement:"tlsAllowInvalidCertificates"}),sslAllowInvalidHostnames:r.default.boolean().optional().register(i.argMetadata,{deprecationReplacement:"tlsAllowInvalidHostnames"}),sslPEMKeyFile:r.default.string().optional().register(i.argMetadata,{deprecationReplacement:"tlsCertificateKeyFile"}),sslPEMKeyPassword:r.default.string().optional().register(i.argMetadata,{deprecationReplacement:"tlsCertificateKeyFilePassword"}),sslCAFile:r.default.string().optional().register(i.argMetadata,{deprecationReplacement:"tlsCAFile"}),sslCertificateSelector:r.default.string().optional().register(i.argMetadata,{deprecationReplacement:"tlsCertificateSelector"}),sslCRLFile:r.default.string().optional().register(i.argMetadata,{deprecationReplacement:"tlsCRLFile"}),sslDisabledProtocols:r.default.string().optional().register(i.argMetadata,{deprecationReplacement:"tlsDisabledProtocols"})}),t.UnsupportedCliOptions=r.default.object({gssapiHostName:r.default.string().optional().register(i.argMetadata,{unsupported:!0}),sslFIPSMode:r.default.boolean().optional().register(i.argMetadata,{unsupported:!0})}),t.CliOptionsSchema=r.default.object({...t.CurrentCliOptionsSchema.shape,...t.DeprecatedCliOptions.shape,...t.UnsupportedCliOptions.shape})},25508:(e,t,o)=>{var n=o(34110).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.Plain=void 0;const r=o(77953),i=o(36997),s=o(30306),a=o(68950);class c extends a.AuthProvider{async auth(e){const{connection:t,credentials:o}=e;if(!o)throw new i.MongoMissingCredentialsError("AuthContext must provide credentials.");const{username:a,password:c}=o,l={saslStart:1,mechanism:"PLAIN",payload:new r.Binary(n.from(`\0${a}\0${c}`)),autoAuthorize:1};await t.command((0,s.ns)("$external.$cmd"),l,void 0)}}t.Plain=c},25859:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FindOperation=void 0;const n=o(72216),r=o(36997),i=o(24007),s=o(30306),a=o(41539),c=o(28947);class l extends a.CommandOperation{constructor(e,t={},o={}){if(super(void 0,o),this.SERVER_COMMAND_RESPONSE_TYPE=n.CursorResponse,this.options={...o},delete this.options.writeConcern,this.ns=e,"object"!=typeof t||Array.isArray(t))throw new r.MongoInvalidArgumentError("Query filter must be a plain object or ObjectId");this.filter=null!=t&&"ObjectId"===t._bsontype?{_id:t}:t,this.SERVER_COMMAND_RESPONSE_TYPE=this.explain?n.ExplainedCursorResponse:n.CursorResponse}get commandName(){return"find"}buildOptions(e){return{...this.options,...this.bsonOptions,documentsReturnedIn:"firstBatch",session:this.session,timeoutContext:e}}handleOk(e){return e}buildCommandDocument(){return function(e,t,o){const n={find:e.collection,filter:t};if(o.sort&&(n.sort=(0,i.formatSort)(o.sort)),o.projection){let e=o.projection;e&&Array.isArray(e)&&(e=e.length?e.reduce(((e,t)=>(e[t]=1,e)),{}):{_id:1}),n.projection=e}return o.hint&&(n.hint=(0,s.normalizeHintField)(o.hint)),"number"==typeof o.skip&&(n.skip=o.skip),"number"==typeof o.limit&&(o.limit<0?(n.limit=-o.limit,n.singleBatch=!0):n.limit=o.limit),"number"==typeof o.batchSize&&(o.batchSize<0?n.limit=-o.batchSize:o.batchSize===o.limit?n.batchSize=o.batchSize+1:n.batchSize=o.batchSize),"boolean"==typeof o.singleBatch&&(n.singleBatch=o.singleBatch),void 0!==o.comment&&(n.comment=o.comment),o.max&&(n.max=o.max),o.min&&(n.min=o.min),"boolean"==typeof o.returnKey&&(n.returnKey=o.returnKey),"boolean"==typeof o.showRecordId&&(n.showRecordId=o.showRecordId),"boolean"==typeof o.tailable&&(n.tailable=o.tailable),"boolean"==typeof o.oplogReplay&&(n.oplogReplay=o.oplogReplay),"boolean"==typeof o.timeout?n.noCursorTimeout=!o.timeout:"boolean"==typeof o.noCursorTimeout&&(n.noCursorTimeout=o.noCursorTimeout),"boolean"==typeof o.awaitData&&(n.awaitData=o.awaitData),"boolean"==typeof o.allowPartialResults&&(n.allowPartialResults=o.allowPartialResults),"boolean"==typeof o.allowDiskUse&&(n.allowDiskUse=o.allowDiskUse),o.let&&(n.let=o.let),n}(this.ns,this.filter,this.options)}}t.FindOperation=l,(0,c.defineAspects)(l,[c.Aspect.READ_OPERATION,c.Aspect.RETRYABLE,c.Aspect.EXPLAINABLE,c.Aspect.CURSOR_CREATING,c.Aspect.SUPPORTS_RAW_DATA])},26119:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DeprioritizedServers=t.MIN_SECONDARY_WRITE_WIRE_VERSION=void 0,t.writableServerSelector=function(){return function(e,t,o){return h(e,c(t.filter((({isWritable:e})=>e)),o))}},t.sameServerSelector=function(e){return function(t,o,n){return e?o.filter((t=>t.address===e.address&&t.type!==i.ServerType.Unknown)):[]}},t.secondaryWritableServerSelector=function(e,o){return!o||!e||e&&e<t.MIN_SECONDARY_WRITE_WIRE_VERSION?y(r.ReadPreference.primary):y(o)},t.readPreferenceServerSelector=y;const n=o(36997),r=o(74891),i=o(90648),s=1e4,a=90;function c(e,t){const o=e.filter((e=>!t.has(e)));return o.length?o:e}function l(e,t,o){if(null==e.maxStalenessSeconds||e.maxStalenessSeconds<0)return o;const r=e.maxStalenessSeconds,c=(t.heartbeatFrequencyMS+s)/1e3;if(r<c)throw new n.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${c} seconds`);if(r<a)throw new n.MongoInvalidArgumentError(`Option "maxStalenessSeconds" must be at least ${a} seconds`);if(t.type===i.TopologyType.ReplicaSetWithPrimary){const n=Array.from(t.servers.values()).filter(m)[0];return o.filter((o=>(o.lastUpdateTime-o.lastWriteDate-(n.lastUpdateTime-n.lastWriteDate)+t.heartbeatFrequencyMS)/1e3<=(e.maxStalenessSeconds??0)))}if(t.type===i.TopologyType.ReplicaSetNoPrimary){if(0===o.length)return o;const n=o.reduce(((e,t)=>t.lastWriteDate>e.lastWriteDate?t:e));return o.filter((o=>(n.lastWriteDate-o.lastWriteDate+t.heartbeatFrequencyMS)/1e3<=(e.maxStalenessSeconds??0)))}return o}function d(e,t){return Object.entries(e).every((([e,o])=>null!=t[e]&&t[e]===o))}function u({tags:e},t){if(null==e||0===e.length)return t;for(const o of e){const e=t.filter((e=>d(o,e.tags)));if(e.length)return e}return[]}function h(e,t){const o=t.reduce(((e,t)=>Math.min(t.roundTripTime,e)),1/0),n=o+e.localThresholdMS;return t.filter((e=>e.roundTripTime<=n&&e.roundTripTime>=o))}function m(e){return e.type===i.ServerType.RSPrimary}function p(e){return e.type===i.ServerType.RSSecondary}function g(e){return e.type===i.ServerType.RSSecondary||e.type===i.ServerType.RSPrimary}function f(e){return e.type!==i.ServerType.Unknown}function S(e){return e.type===i.ServerType.LoadBalancer}function E(e){return t=>!e.has(t)}function y(e){if(!e.isValid())throw new n.MongoInvalidArgumentError("Invalid read preference specified");return function(t,o,i){switch(t.type){case"Single":return h(t,o.filter(f));case"ReplicaSetNoPrimary":case"ReplicaSetWithPrimary":return function(e,t,o,i){const s=e.mode;switch(s){case"primary":return o.filter(m);case"primaryPreferred":{const n=o.filter(m),r=n.filter(E(i));if(r.length)return r;const s=u(e,l(e,t,o.filter(p))),a=s.filter(E(i));return a.length?h(t,a):n.length?n:h(t,s)}case"nearest":return h(t,c(u(e,l(e,t,o.filter(g))),i));case"secondary":case"secondaryPreferred":{const n=u(e,l(e,t,o.filter(p))),a=n.filter(E(i));if(a.length)return h(t,a);if(s===r.ReadPreference.SECONDARY_PREFERRED){const e=o.filter(m),r=e.filter(E(i));return r.length?r:n.length?h(t,n):e}return h(t,n)}default:throw new n.MongoRuntimeError(`unexpected readPreference=${s} (should never happen). Please report a bug in the Node driver Jira project.`)}}(e,t,o,i);case"Sharded":return h(t,c(o,i).filter(f));case"Unknown":return[];case"LoadBalanced":return o.filter(S);default:throw t.type,new n.MongoRuntimeError(`unexpected topology type: ${t.type} (this should never happen). Please file a bug in the Node driver Jira project.`)}}}t.MIN_SECONDARY_WRITE_WIRE_VERSION=13,t.DeprioritizedServers=class{constructor(e){this.deprioritized=new Set;for(const t of e??[])this.add(t)}add({address:e}){this.deprioritized.add(e)}has({address:e}){return this.deprioritized.has(e)}}},26482:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.callback=void 0;const n=o(4308),r=o(15088),i=o(36997);t.callback=async()=>{const e=r.env.OIDC_TOKEN_FILE;if(!e)throw new i.MongoAWSError("OIDC_TOKEN_FILE must be set in the environment.");return{accessToken:await n.promises.readFile(e,"utf8")}}},27272:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Explain=t.ExplainVerbosity=void 0,t.validateExplainTimeoutOptions=function(e,t){const{maxTimeMS:o,timeoutMS:r}=e;if(null!=r&&(null!=o||null!=t?.maxTimeMS))throw new n.MongoAPIError("Cannot use maxTimeMS with timeoutMS for explain commands.")},t.decorateWithExplain=function(e,t){const{verbosity:o,maxTimeMS:n}=t,r={explain:e,verbosity:o};return"number"==typeof n&&(r.maxTimeMS=n),r};const n=o(36997);t.ExplainVerbosity=Object.freeze({queryPlanner:"queryPlanner",queryPlannerExtended:"queryPlannerExtended",executionStats:"executionStats",allPlansExecution:"allPlansExecution"});class r{constructor(e,o){this.verbosity="boolean"==typeof e?e?t.ExplainVerbosity.allPlansExecution:t.ExplainVerbosity.queryPlanner:e,this.maxTimeMS=o}static fromOptions({explain:e}={}){if(null==e)return;if("boolean"==typeof e||"string"==typeof e)return new r(e);const{verbosity:t,maxTimeMS:o}=e;return new r(t,o)}}t.Explain=r},27827:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DeleteManyOperation=t.DeleteOneOperation=t.DeleteOperation=void 0,t.makeDeleteStatement=u;const n=o(72216),r=o(36997),i=o(30306),s=o(41539),a=o(28947);class c extends s.CommandOperation{constructor(e,t,o){super(void 0,o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=o,this.ns=e,this.statements=t}get commandName(){return"delete"}get canRetryWrite(){return!1!==super.canRetryWrite&&this.statements.every((e=>null==e.limit||e.limit>0))}buildCommandDocument(e,t){const o=this.options,n="boolean"!=typeof o.ordered||o.ordered,s={delete:this.ns.collection,deletes:this.statements,ordered:n};if(o.let&&(s.let=o.let),void 0!==o.comment&&(s.comment=o.comment),this.writeConcern&&0===this.writeConcern.w&&(0,i.maxWireVersion)(e)<9&&this.statements.find((e=>e.hint)))throw new r.MongoCompatibilityError("hint for the delete command is only supported on MongoDB 4.4+");return s}}t.DeleteOperation=c;class l extends c{constructor(e,t,o){super(e,[u(t,{...o,limit:1})],o)}handleOk(e){const t=super.handleOk(e);if(this.explain)return t;if(t.code)throw new r.MongoServerError(t);if(t.writeErrors)throw new r.MongoServerError(t.writeErrors[0]);return{acknowledged:0!==this.writeConcern?.w,deletedCount:t.n}}}t.DeleteOneOperation=l;class d extends c{constructor(e,t,o){super(e,[u(t,o)],o)}handleOk(e){const t=super.handleOk(e);if(this.explain)return t;if(t.code)throw new r.MongoServerError(t);if(t.writeErrors)throw new r.MongoServerError(t.writeErrors[0]);return{acknowledged:0!==this.writeConcern?.w,deletedCount:t.n}}}function u(e,t){const o={q:e,limit:"number"==typeof t.limit?t.limit:0};return t.collation&&(o.collation=t.collation),t.hint&&(o.hint=t.hint),o}t.DeleteManyOperation=d,(0,a.defineAspects)(c,[a.Aspect.RETRYABLE,a.Aspect.WRITE_OPERATION,a.Aspect.SUPPORTS_RAW_DATA]),(0,a.defineAspects)(l,[a.Aspect.RETRYABLE,a.Aspect.WRITE_OPERATION,a.Aspect.EXPLAINABLE,a.Aspect.SKIP_COLLATION,a.Aspect.SUPPORTS_RAW_DATA]),(0,a.defineAspects)(d,[a.Aspect.WRITE_OPERATION,a.Aspect.EXPLAINABLE,a.Aspect.SKIP_COLLATION,a.Aspect.SUPPORTS_RAW_DATA])},28749:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},28777:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.finishCommandDocument=function(e,t){return null!=t?{saslContinue:1,conversationId:t,payload:new n.Binary(n.BSON.serialize({jwt:e}))}:{saslStart:1,mechanism:r.AuthMechanism.MONGODB_OIDC,payload:new n.Binary(n.BSON.serialize({jwt:e}))}},t.startCommandDocument=function(e){const t={};return e.username&&(t.n=e.username),{saslStart:1,autoAuthorize:1,mechanism:r.AuthMechanism.MONGODB_OIDC,payload:new n.Binary(n.BSON.serialize(t))}};const n=o(77953),r=o(65070)},28947:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractOperation=t.Aspect=void 0,t.defineAspects=function(e,t){return Array.isArray(t)||t instanceof Set||(t=[t]),t=new Set(t),Object.defineProperty(e,"aspects",{value:t,writable:!1}),t};const n=o(77953),r=o(74891);t.Aspect={READ_OPERATION:Symbol("READ_OPERATION"),WRITE_OPERATION:Symbol("WRITE_OPERATION"),RETRYABLE:Symbol("RETRYABLE"),EXPLAINABLE:Symbol("EXPLAINABLE"),SKIP_COLLATION:Symbol("SKIP_COLLATION"),CURSOR_CREATING:Symbol("CURSOR_CREATING"),MUST_SELECT_SAME_SERVER:Symbol("MUST_SELECT_SAME_SERVER"),COMMAND_BATCHING:Symbol("COMMAND_BATCHING"),SUPPORTS_RAW_DATA:Symbol("SUPPORTS_RAW_DATA")},t.AbstractOperation=class{constructor(e={}){this.readPreference=this.hasAspect(t.Aspect.WRITE_OPERATION)?r.ReadPreference.primary:r.ReadPreference.fromOptions(e)??r.ReadPreference.primary,this.bsonOptions=(0,n.resolveBSONOptions)(e),this._session=null!=e.session?e.session:void 0,this.options=e,this.bypassPinningCheck=!!e.bypassPinningCheck}hasAspect(e){const t=this.constructor;return null!=t.aspects&&t.aspects.has(e)}get session(){return this._session}set session(e){this._session=e}clearSession(){this._session=void 0}resetBatch(){return!0}get canRetryRead(){return this.hasAspect(t.Aspect.RETRYABLE)&&this.hasAspect(t.Aspect.READ_OPERATION)}get canRetryWrite(){return this.hasAspect(t.Aspect.RETRYABLE)&&this.hasAspect(t.Aspect.WRITE_OPERATION)}handleOk(e){return e.toObject(this.bsonOptions)}handleError(e){throw e}}},29016:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoDBAWS=void 0;const n=o(77953),r=o(36997),i=o(30306),s=o(68950),a=o(71260),c=o(51641),l=o(32985),d=o(65070),u={useBigInt64:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1};class h extends s.AuthProvider{constructor(e){super(),this.credentialFetcher=new a.AWSSDKCredentialProvider(e)}async auth(e){const{connection:t}=e;if(!e.credentials)throw new r.MongoMissingCredentialsError("AuthContext must provide credentials.");if((0,i.maxWireVersion)(t)<9)throw new r.MongoCompatibilityError("MONGODB-AWS authentication requires MongoDB version 4.4 or later");e.credentials=await async function(e,t){return function(t){if(!t.AccessKeyId||!t.SecretAccessKey)throw new r.MongoMissingCredentialsError("Could not obtain temporary MONGODB-AWS credentials");return new l.MongoCredentials({username:t.AccessKeyId,password:t.SecretAccessKey,source:e.source,mechanism:d.AuthMechanism.MONGODB_AWS,mechanismProperties:{AWS_SESSION_TOKEN:t.Token}})}(await t.getCredentials())}(e.credentials,this.credentialFetcher);const{credentials:o}=e,s=o.username,a=o.password,h=o.mechanismProperties.AWS_SESSION_TOKEN,p=h?{accessKeyId:s,secretAccessKey:a,sessionToken:h}:{accessKeyId:s,secretAccessKey:a},g=o.source,f=await(0,i.randomBytes)(32),S={saslStart:1,mechanism:"MONGODB-AWS",payload:n.serialize({r:f,p:110},u)},E=await t.command((0,i.ns)(`${g}.$cmd`),S,void 0),y=n.deserialize(E.payload.buffer,u),b=y.h,O=y.s.buffer;if(64!==O.length)throw new r.MongoRuntimeError(`Invalid server nonce length ${O.length}, expected 64`);if(!i.ByteUtils.equals(O.subarray(0,f.byteLength),f))throw new r.MongoRuntimeError("Server nonce does not begin with client nonce");if(b.length<1||b.length>255||-1!==b.indexOf(".."))throw new r.MongoRuntimeError(`Server returned an invalid host: "${b}"`);const C=await(0,c.aws4Sign)({method:"POST",host:b,region:m(y.h),service:"sts",headers:{"Content-Type":"application/x-www-form-urlencoded","Content-Length":43,"X-MongoDB-Server-Nonce":i.ByteUtils.toBase64(O),"X-MongoDB-GS2-CB-Flag":"n"},path:"/",body:"Action=GetCallerIdentity&Version=2011-06-15",date:new Date},p),M={a:C.Authorization,d:C["X-Amz-Date"]};h&&(M.t=h);const T={saslContinue:1,conversationId:E.conversationId,payload:n.serialize(M,u)};await t.command((0,i.ns)(`${g}.$cmd`),T,void 0)}}function m(e){const t=e.split(".");return 1===t.length||"amazonaws"===t[1]?"us-east-1":t[1]}t.MongoDBAWS=h},29976:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DistinctOperation=void 0;const n=o(72216),r=o(41539),i=o(28947);class s extends r.CommandOperation{constructor(e,t,o,r){super(e,r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=r??{},this.collection=e,this.key=t,this.query=o}get commandName(){return"distinct"}buildCommandDocument(e){const t={distinct:this.collection.collectionName,key:this.key,query:this.query};return void 0!==this.options.comment&&(t.comment=this.options.comment),null!=this.options.hint&&(t.hint=this.options.hint),t}handleOk(e){return this.explain?e.toObject(this.bsonOptions):e.toObject(this.bsonOptions).values}}t.DistinctOperation=s,(0,i.defineAspects)(s,[i.Aspect.READ_OPERATION,i.Aspect.RETRYABLE,i.Aspect.EXPLAINABLE,i.Aspect.SUPPORTS_RAW_DATA])},30306:(e,t,o)=>{var n=o(34110).Buffer,r=o(21655).URL;Object.defineProperty(t,"__esModule",{value:!0}),t.kDispose=t.randomBytes=t.COSMOS_DB_MSG=t.DOCUMENT_DB_MSG=t.COSMOS_DB_CHECK=t.DOCUMENT_DB_CHECK=t.MONGODB_WARNING_CODE=t.DEFAULT_PK_FACTORY=t.HostAddress=t.BufferPool=t.List=t.MongoDBCollectionNamespace=t.MongoDBNamespace=t.ByteUtils=void 0,t.isUint8Array=function(e){return null!=e&&"object"==typeof e&&Symbol.toStringTag in e&&"Uint8Array"===e[Symbol.toStringTag]},t.hostMatchesWildcards=function(e,t){for(const o of t){if(e===o)return!0;if(o.startsWith("*.")){const t=o.substring(2);if(e===t||e.endsWith(`.${t}`))return!0}if(o.startsWith("*/")){const t=o.substring(2);if(e===t||e.endsWith(`/${t}`))return!0}}return!1},t.normalizeHintField=function(e){let t;if("string"==typeof e)t=e;else if(Array.isArray(e))t={},e.forEach((e=>{t[e]=1}));else if(null!=e&&"object"==typeof e){t={};for(const o in e)t[o]=e[o]}return t},t.isObject=y,t.mergeOptions=function(e,t){return{...e,...t}},t.filterOptions=function(e,t){const o={};for(const n in e)t.includes(n)&&(o[n]=e[n]);return o},t.isPromiseLike=function(e){return null!=e&&"object"==typeof e&&"then"in e&&"function"==typeof e.then},t.decorateWithCollation=function(e,t){t.collation&&"object"==typeof t.collation&&(e.collation=t.collation)},t.decorateWithReadConcern=function(e,t,o){if(o&&o.session&&o.session.inTransaction())return;const n=Object.assign({},e.readConcern||{});t.s.readConcern&&Object.assign(n,t.s.readConcern),Object.keys(n).length>0&&Object.assign(e,{readConcern:n})},t.getTopology=function(e){if("topology"in e&&e.topology)return e.topology;if("client"in e&&e.client.topology)return e.client.topology;throw new m.MongoNotConnectedError("MongoClient must be connected to perform this operation")},t.ns=function(e){return b.fromString(e)},t.makeCounter=function*(e=0){let t=e;for(;;){const e=t;t+=1,yield e}},t.uuidV4=function(){const e=i.randomBytes(16);return e[6]=15&e[6]|64,e[8]=63&e[8]|128,e},t.maxWireVersion=function(e){if(e){if(e.hello)return e.hello.maxWireVersion;if(e.serverApi?.version)return u.MAX_SUPPORTED_WIRE_VERSION;if(e.loadBalanced)return u.MAX_SUPPORTED_WIRE_VERSION;if("lastHello"in e&&"function"==typeof e.lastHello){const t=e.lastHello();if(t)return t.maxWireVersion}if(e.description&&"maxWireVersion"in e.description&&null!=e.description.maxWireVersion)return e.description.maxWireVersion}return 0},t.arrayStrictEqual=function(e,t){return!(!Array.isArray(e)||!Array.isArray(t))&&(e.length===t.length&&e.every(((e,o)=>e===t[o])))},t.errorStrictEqual=function(e,t){return e===t||(e&&t?!(null==e&&null!=t||null!=e&&null==t)&&(e.constructor.name===t.constructor.name&&e.message===t.message):e===t)},t.makeStateMachine=function(e){return function(t,o){const n=e[t.s.state];if(n&&n.indexOf(o)<0)throw new m.MongoRuntimeError(`illegal state transition from [${t.s.state}] => [${o}], allowed: [${n}]`);t.emit("stateChanged",t.s.state,o),t.s.state=o}},t.processTimeMS=C,t.calculateDurationInMs=function(e){if("number"!=typeof e)return-1;const t=C()-e;return t<0?0:t},t.hasAtomicOperators=function e(t,o){if(Array.isArray(t)){for(const o of t)if(e(o))return!0;return!1}const n=Object.keys(t);if(o?.ignoreUndefined){let e=!0;for(const o of n)if(void 0!==t[o]){e=!1;break}if(e)throw new m.MongoInvalidArgumentError("Update operations require that all atomic operators have defined values, but none were provided.")}return n.length>0&&"$"===n[0][0]},t.resolveTimeoutOptions=function(e,t){const{socketTimeoutMS:o,serverSelectionTimeoutMS:n,waitQueueTimeoutMS:r,timeoutMS:i}=e.s.options;return{socketTimeoutMS:o,serverSelectionTimeoutMS:n,waitQueueTimeoutMS:r,timeoutMS:i,...t}},t.resolveOptions=function(e,t){const o=Object.assign({},t,(0,d.resolveBSONOptions)(t,e)),n=t?.timeoutMS??e?.timeoutMS,r=t?.session;if(!r?.inTransaction()){const r=p.ReadConcern.fromOptions(t)??e?.readConcern;r&&(o.readConcern=r);let i=S.WriteConcern.fromOptions(t)??e?.writeConcern;i&&(null!=n&&(i=S.WriteConcern.fromOptions({writeConcern:{...i,wtimeout:void 0,wtimeoutMS:void 0}})),o.writeConcern=i)}o.timeoutMS=n;const i=g.ReadPreference.fromOptions(t)??e?.readPreference;if(i&&(o.readPreference=i),r?.explicit&&null!=r?.timeoutContext&&null!=t?.timeoutMS)throw new m.MongoInvalidArgumentError("An operation cannot be given a timeoutMS setting when inside a withTransaction call that has a timeoutMS setting");return o},t.isSuperset=M,t.isHello=function(e){return!(!e[h.LEGACY_HELLO_COMMAND]&&!e.hello)},t.setDifference=function(e,t){const o=new Set(e);for(const e of t)o.delete(e);return o},t.isRecord=function(e,t=void 0){if(!y(e))return!1;const o=e.constructor;if(o&&o.prototype){if(!y(o.prototype))return!1;if(!T(o.prototype,"isPrototypeOf"))return!1}return!t||M(Object.keys(e),t)},t.emitWarning=R,t.emitWarningOnce=function(e){if(!A.has(e))return A.add(e),R(e)},t.enumToString=function(e){return Object.values(e).join(", ")},t.supportsRetryableWrites=function(e){return!!e&&(!!e.loadBalanced||null!=e.description.logicalSessionTimeoutMinutes&&e.description.type!==f.ServerType.Standalone)},t.shuffle=function(e,t=0){const o=Array.from(e);if(t>o.length)throw new m.MongoRuntimeError("Limit must be less than the number of items");let n=o.length;const r=t%o.length==0?1:o.length-t;for(;n>r;){const e=Math.floor(Math.random()*n);n-=1;const t=o[n];o[n]=o[e],o[e]=t}return t%o.length==0?o:o.slice(r)},t.commandSupportsReadConcern=function(e){return!!(e.aggregate||e.count||e.distinct||e.find||e.geoNear)},t.compareObjectId=function(e,o){return null==e&&null==o?0:null==e?-1:null==o?1:t.ByteUtils.compare(e.id,o.id)},t.parseInteger=_,t.parseUnsignedInteger=function(e){const t=_(e);return null!=t&&t>=0?t:null},t.checkParentDomainMatch=function(e,t){const o=e.endsWith(".")?e.slice(0,e.length-1):e,n=t.endsWith(".")?t.slice(0,t.length-1):t,r=/^.*?\./,i=n.split(".").length<3,s=`.${o.replace(r,"")}`;let a=i?n:`.${n.replace(r,"")}`;if(a.startsWith(".")||(a="."+a),i&&o.split(".").length<=n.split(".").length)throw new m.MongoAPIError("Server record does not have at least one more domain level than parent URI");if(!s.endsWith(a))throw new m.MongoAPIError("Server record does not share hostname with parent URI")},t.get=function(e,t={}){return new Promise(((o,n)=>{let r;const i=a.get(e,t,(e=>{e.setEncoding("utf8");let t="";e.on("data",(e=>t+=e)),e.on("end",(()=>{(0,l.clearTimeout)(r),o({status:e.statusCode,body:t})}))})).on("error",(e=>{(0,l.clearTimeout)(r),n(e)})).end();r=(0,l.setTimeout)((()=>{i.destroy(new m.MongoNetworkTimeoutError("request timed out after 10 seconds"))}),1e4)}))},t.isHostMatch=function(e,t){return!(!t||!e.test(t.toLowerCase()))},t.promiseWithResolvers=I,t.squashError=function(e){},t.once=async function(e,o,n){n?.signal?.throwIfAborted();const{promise:r,resolve:i,reject:s}=I(),a=e=>i(e),c=e=>s(e),l=N(n?.signal,(function(){s(this.reason)}));e.once(o,a).once("error",c);try{return await r}finally{e.off(o,a),e.off("error",c),l?.[t.kDispose]()}},t.maybeAddIdToDocuments=function(e,t,o){return(o.forceServerObjectId??e.db.options?.forceServerObjectId)||null==t._id&&(t._id=e.s.pkFactory.createPk()),t},t.fileIsAccessible=async function(e,t){try{return await s.promises.access(e,t),!0}catch{return!1}},t.csotMin=function(e,t){return 0===e?t:0===t?e:Math.min(e,t)},t.noop=function(){},t.decorateDecryptionResult=function e(t,o,r=!0){if(r&&(n.isBuffer(o)&&(o=(0,d.deserialize)(o)),n.isBuffer(t)))throw new m.MongoRuntimeError("Expected result of decryption to be deserialized BSON object");if(t&&"object"==typeof t)for(const n of Object.keys(t)){const r=o[n];r&&"Binary"===r._bsontype&&6===r.sub_type?(t[h.kDecoratedKeys]||Object.defineProperty(t,h.kDecoratedKeys,{value:[],configurable:!0,enumerable:!1,writable:!1}),t[h.kDecoratedKeys].push(n)):e(t[n],r,!1)}},t.addAbortListener=N,t.abortable=async function(e,{signal:o}){if(null==o)return await e;const{promise:n,reject:r}=I(),i=o.aborted?r(o.reason):N(o,(function(){r(this.reason)}));try{return await Promise.race([e,n])}finally{i?.[t.kDispose]()}};const i=o(97359),s=o(4308),a=o(7742),c=o(15088),l=o(31713),d=o(77953),u=o(60889),h=o(34842),m=o(36997),p=o(86552),g=o(74891),f=o(90648),S=o(71259);t.ByteUtils={toLocalBufferType:e=>n.isBuffer(e)?e:n.from(e.buffer,e.byteOffset,e.byteLength),equals:(e,o)=>t.ByteUtils.toLocalBufferType(e).equals(o),compare:(e,o)=>t.ByteUtils.toLocalBufferType(e).compare(o),toBase64:e=>t.ByteUtils.toLocalBufferType(e).toString("base64")};const E=e=>Object.prototype.toString.call(e);function y(e){return"[object Object]"===E(e)}class b{constructor(e,t){this.db=e,this.collection=""===t?void 0:t}toString(){return this.collection?`${this.db}.${this.collection}`:this.db}withCollection(e){return new O(this.db,e)}static fromString(e){if("string"!=typeof e||""===e)throw new m.MongoRuntimeError(`Cannot parse namespace from "${e}"`);const[t,...o]=e.split("."),n=o.join(".");return new b(t,""===n?void 0:n)}}t.MongoDBNamespace=b;class O extends b{constructor(e,t){super(e,t),this.collection=t}static fromString(e){return super.fromString(e)}}function C(){return Math.floor(performance.now())}function M(e,t){e=Array.isArray(e)?new Set(e):e,t=Array.isArray(t)?new Set(t):t;for(const o of t)if(!e.has(o))return!1;return!0}t.MongoDBCollectionNamespace=O;const T=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);class w{get length(){return this.count}get[Symbol.toStringTag](){return"List"}constructor(){this.count=0,this.head={next:null,prev:null,value:null},this.head.next=this.head,this.head.prev=this.head}toArray(){return Array.from(this)}toString(){return`head <=> ${this.toArray().join(" <=> ")} <=> head`}*[Symbol.iterator](){for(const e of this.nodes())yield e.value}*nodes(){let e=this.head.next;for(;e!==this.head;){const{next:t}=e;yield e,e=t}}push(e){this.count+=1;const t={next:this.head,prev:this.head.prev,value:e};this.head.prev.next=t,this.head.prev=t}pushMany(e){for(const t of e)this.push(t)}unshift(e){this.count+=1;const t={next:this.head.next,prev:this.head,value:e};this.head.next.prev=t,this.head.next=t}remove(e){if(e===this.head||0===this.length)return null;this.count-=1;const t=e.prev,o=e.next;return t.next=o,o.prev=t,e.value}shift(){return this.remove(this.head.next)}pop(){return this.remove(this.head.prev)}prune(e){for(const t of this.nodes())e(t.value)&&this.remove(t)}clear(){this.count=0,this.head.next=this.head,this.head.prev=this.head}first(){return this.head.next.value}last(){return this.head.prev.value}}t.List=w,t.BufferPool=class{constructor(){this.buffers=new w,this.totalByteLength=0}get length(){return this.totalByteLength}append(e){this.buffers.push(e),this.totalByteLength+=e.length}getInt32(){if(this.totalByteLength<4)return null;const e=this.buffers.first();if(null!=e&&e.byteLength>=4)return e.readInt32LE(0);const t=this.read(4),o=t.readInt32LE(0);return this.totalByteLength+=4,this.buffers.unshift(t),o}read(e){if("number"!=typeof e||e<0)throw new m.MongoInvalidArgumentError('Argument "size" must be a non-negative number');if(e>this.totalByteLength)return n.alloc(0);const t=n.allocUnsafe(e);for(let o=0;o<e;){const n=this.buffers.shift();if(null==n)break;const r=e-o,i=Math.min(r,n.byteLength),s=n.subarray(0,i);t.set(s,o),o+=i,this.totalByteLength-=i,i<n.byteLength&&this.buffers.unshift(n.subarray(i))}return t}};class v{constructor(e){this.host=void 0,this.port=void 0,this.socketPath=void 0,this.isIPv6=!1;const t=e.split(" ").join("%20");if(t.endsWith(".sock"))return void(this.socketPath=decodeURIComponent(t));const o=`iLoveJS://${t}`;let n;try{n=new r(o)}catch(e){const o=new m.MongoRuntimeError(`Unable to parse ${t} with URL`);throw o.cause=e,o}const i=n.hostname,s=n.port;let a=decodeURIComponent(i).toLowerCase();if(a.startsWith("[")&&a.endsWith("]")&&(this.isIPv6=!0,a=a.substring(1,i.length-1)),this.host=a.toLowerCase(),this.port="number"==typeof s?s:"string"==typeof s&&""!==s?Number.parseInt(s,10):27017,0===this.port)throw new m.MongoParseError("Invalid port (zero) with hostname");Object.freeze(this)}[Symbol.for("nodejs.util.inspect.custom")](){return this.inspect()}inspect(){return`new HostAddress('${this.toString()}')`}toString(){return"string"==typeof this.host?this.isIPv6?`[${this.host}]:${this.port}`:`${this.host}:${this.port}`:`${this.socketPath}`}static fromString(e){return new v(e)}static fromHostPort(e,t){return e.includes(":")&&(e=`[${e}]`),v.fromString(`${e}:${t}`)}static fromSrvRecord({name:e,port:t}){return v.fromHostPort(e,t)}toHostPort(){return this.socketPath?{host:this.socketPath,port:0}:{host:this.host??"",port:this.port??0}}}function R(e){return c.emitWarning(e,{code:t.MONGODB_WARNING_CODE})}t.HostAddress=v,t.DEFAULT_PK_FACTORY={createPk:()=>new d.ObjectId},t.MONGODB_WARNING_CODE="MONGODB DRIVER";const A=new Set;function _(e){if("number"==typeof e)return Math.trunc(e);const t=Number.parseInt(String(e),10);return Number.isNaN(t)?null:t}function I(){let e,t;return{promise:new Promise((function(o,n){e=o,t=n})),resolve:e,reject:t}}function N(e,o){if(null!=e)return e.addEventListener("abort",o,{once:!0}),{[t.kDispose]:()=>e.removeEventListener("abort",o)}}t.DOCUMENT_DB_CHECK=/(\.docdb\.amazonaws\.com$)|(\.docdb-elastic\.amazonaws\.com$)/,t.COSMOS_DB_CHECK=/\.cosmos\.azure\.com$/,t.DOCUMENT_DB_MSG="You appear to be connected to a DocumentDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/documentdb",t.COSMOS_DB_MSG="You appear to be connected to a CosmosDB cluster. For more information regarding feature compatibility and support please visit https://www.mongodb.com/supportability/cosmosdb",t.randomBytes=e=>new Promise(((t,o)=>{i.randomBytes(e,((e,n)=>{if(e)return o(e);t(n)}))})),t.kDispose=Symbol.dispose??Symbol("dispose")},30427:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoClientAuthProviders=void 0;const n=o(21427),r=o(29016),i=o(41720),s=o(87187),a=o(20552),c=o(60239),l=o(25508),d=o(65070),u=o(4530),h=o(48570),m=o(36997),p=new Map([[d.AuthMechanism.MONGODB_AWS,({AWS_CREDENTIAL_PROVIDER:e})=>new r.MongoDBAWS(e)],[d.AuthMechanism.MONGODB_GSSAPI,()=>new n.GSSAPI],[d.AuthMechanism.MONGODB_OIDC,e=>new i.MongoDBOIDC(function(e){if(e.OIDC_HUMAN_CALLBACK)return new a.HumanCallbackWorkflow(new c.TokenCache,e.OIDC_HUMAN_CALLBACK);if(e.OIDC_CALLBACK)return new s.AutomatedCallbackWorkflow(new c.TokenCache,e.OIDC_CALLBACK);{const t=e.ENVIRONMENT,o=i.OIDC_WORKFLOWS.get(t)?.();if(!o)throw new m.MongoInvalidArgumentError(`Could not load workflow for environment ${e.ENVIRONMENT}`);return o}}(e))],[d.AuthMechanism.MONGODB_PLAIN,()=>new l.Plain],[d.AuthMechanism.MONGODB_SCRAM_SHA1,()=>new u.ScramSHA1],[d.AuthMechanism.MONGODB_SCRAM_SHA256,()=>new u.ScramSHA256],[d.AuthMechanism.MONGODB_X509,()=>new h.X509]]);t.MongoClientAuthProviders=class{constructor(){this.existingProviders=new Map}getOrCreateProvider(e,t){const o=this.existingProviders.get(e);if(o)return o;const n=p.get(e);if(!n)throw new m.MongoInvalidArgumentError(`authMechanism ${e} not supported`);const r=n(t);return this.existingProviders.set(e,r),r}}},30633:function(e,t,o){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.CliOptionsSchema=t.UnsupportedArgumentError=t.UnknownArgumentError=t.argMetadata=t.defaultParserOptions=void 0,t.createParseArgs=l,t.createParseArgsWithCliOptions=function({schema:e,parserOptions:t}={}){const o=l({schema:void 0!==e?i.z.object({...s.CliOptionsSchema.shape,...e.shape}):s.CliOptionsSchema,parserOptions:t});return({args:e})=>{const{parsed:t,positional:n,deprecated:r}=o({args:e}),i=(0,s.processPositionalCliOptions)({parsed:t,positional:n});return(0,s.validateCliOptions)(i),{parsed:i,positional:n,deprecated:r}}},t.generateYargsOptionsFromSchema=d,t.getLocale=function(e,t){const o=e.indexOf("--locale");if(o>-1)return e[o+1];const n=t.LANG||t.LANGUAGE||t.LC_ALL||t.LC_MESSAGES;return n?n.split(".")[0]:n};const r=n(o(35384)),i=o(99539),s=o(24968),a=o(3803);Object.defineProperty(t,"argMetadata",{enumerable:!0,get:function(){return a.argMetadata}}),Object.defineProperty(t,"UnknownArgumentError",{enumerable:!0,get:function(){return a.UnknownArgumentError}}),Object.defineProperty(t,"UnsupportedArgumentError",{enumerable:!0,get:function(){return a.UnsupportedArgumentError}});const c=o(48384);function l({schema:e,parserOptions:t}){const o=d({schema:e,parserOptions:t});return({args:t})=>{const{argv:n,error:s}=r.default.detailed(t,{...o}),{_:c,...l}=n;if(s){if(s instanceof i.ZodError)throw new a.InvalidArgumentError(s.message);throw s}const d=(0,a.getDeprecatedArgsWithReplacement)(e),u={};for(const e of Object.keys(d))if(e in l){const t=d[e];l[t]=l[e],u[e]=t,delete l[e]}for(const e of c)if("string"==typeof e&&e.startsWith("-"))throw new a.UnknownArgumentError(e);const h=(0,a.getUnsupportedArgs)(e);for(const e of h)if(e in l)throw new a.UnsupportedArgumentError(e);return{parsed:l,deprecated:u,positional:c}}}function d({schema:e,parserOptions:o=t.defaultParserOptions}){const n={...o,string:[],boolean:[],array:[],alias:{},coerce:{},number:[]};return function e(t,o=""){for(const[r,s]of Object.entries(t.shape)){const l=o?`${o}.${r}`:r,d=(0,a.getArgumentMetadata)(t,r),u=(0,c.unwrapType)(s);if(u instanceof i.z.ZodArray)n.array.push(l);else if(u instanceof i.z.ZodBoolean)n.boolean.push(l);else if(u instanceof i.z.ZodString)n.string.push(l);else if(u instanceof i.z.ZodNumber)n.number.push(l);else if(u instanceof i.z.ZodUnion){const e=u.options;if(e.some((e=>e instanceof i.z.ZodString||e instanceof i.z.ZodEnum))){const t=e.some((e=>e instanceof i.z.ZodLiteral&&!1===e.value)),o=e.some((e=>e instanceof i.z.ZodBoolean));t?(n.coerce[l]=c.coerceIfFalse,n.string.push(l)):o?n.coerce[l]=c.coerceIfBoolean:n.string.push(l)}}else if(u instanceof i.z.ZodEnum)if(u.options.every((e=>"string"==typeof e)))n.string.push(l);else{if(!u.options.every((e=>"number"==typeof e)))throw new Error(`${l} has unsupported enum options. Currently, only string and number enum options are supported.`);n.number.push(l)}else{if(!(u instanceof i.z.ZodObject))throw new Error(`Unknown field type: ${u instanceof Object?u.constructor.name:typeof u}`);o||(n.coerce[l]=(0,c.coerceObject)(u)),e(u,l)}if(!o&&d?.alias)for(const e of d.alias)n.alias[e]=l}}(e),n}t.defaultParserOptions={configuration:{"camel-case-expansion":!1,"unknown-options-as-args":!0,"parse-positional-numbers":!1,"parse-numbers":!1,"greedy-arrays":!1,"short-option-groups":!1}};var u=o(24968);Object.defineProperty(t,"CliOptionsSchema",{enumerable:!0,get:function(){return u.CliOptionsSchema}})},31353:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CompassServiceProvider=void 0;const n=o(34023);class r extends n.NodeDriverServiceProvider{constructor(e,t,o,n,r){super(e,t,o,n,r),this.platform="Compass"}}t.CompassServiceProvider=r},32178:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CompassServiceProvider=t.NodeDriverServiceProvider=void 0;const n=o(34023);Object.defineProperty(t,"NodeDriverServiceProvider",{enumerable:!0,get:function(){return n.NodeDriverServiceProvider}});const r=o(31353);Object.defineProperty(t,"CompassServiceProvider",{enumerable:!0,get:function(){return r.CompassServiceProvider}})},32328:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnorderedBulkOperation=void 0;const n=o(77953),r=o(36997),i=o(82403);class s extends i.BulkOperationBase{constructor(e,t){super(e,t,!1)}handleWriteError(e){if(!this.s.batches.length)return super.handleWriteError(e)}addToOperationsList(e,t){const o=n.calculateObjectSize(t,{checkKeys:!1,ignoreUndefined:!1});if(o>=this.s.maxBsonObjectSize)throw new r.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`);this.s.currentBatch=void 0,e===i.BatchType.INSERT?this.s.currentBatch=this.s.currentInsertBatch:e===i.BatchType.UPDATE?this.s.currentBatch=this.s.currentUpdateBatch:e===i.BatchType.DELETE&&(this.s.currentBatch=this.s.currentRemoveBatch);const s=this.s.maxKeySize;if(null==this.s.currentBatch&&(this.s.currentBatch=new i.Batch(e,this.s.currentIndex)),(this.s.currentBatch.size+1>=this.s.maxWriteBatchSize||this.s.currentBatch.size>0&&this.s.currentBatch.sizeBytes+s+o>=this.s.maxBatchSizeBytes||this.s.currentBatch.batchType!==e)&&(this.s.batches.push(this.s.currentBatch),this.s.currentBatch=new i.Batch(e,this.s.currentIndex)),Array.isArray(t))throw new r.MongoInvalidArgumentError("Operation passed in cannot be an Array");return this.s.currentBatch.operations.push(t),this.s.currentBatch.originalIndexes.push(this.s.currentIndex),this.s.currentIndex=this.s.currentIndex+1,e===i.BatchType.INSERT?(this.s.currentInsertBatch=this.s.currentBatch,this.s.bulkResult.insertedIds.push({index:this.s.bulkResult.insertedIds.length,_id:t._id})):e===i.BatchType.UPDATE?this.s.currentUpdateBatch=this.s.currentBatch:e===i.BatchType.DELETE&&(this.s.currentRemoveBatch=this.s.currentBatch),this.s.currentBatch.size+=1,this.s.currentBatch.sizeBytes+=s+o,this}}t.UnorderedBulkOperation=s},32583:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServerDescription=void 0,t.parseServerType=l,t.compareTopologyVersion=d;const n=o(77953),r=o(36997),i=o(30306),s=o(90648),a=new Set([s.ServerType.RSPrimary,s.ServerType.Standalone,s.ServerType.Mongos,s.ServerType.LoadBalancer]),c=new Set([s.ServerType.RSPrimary,s.ServerType.RSSecondary,s.ServerType.Mongos,s.ServerType.Standalone,s.ServerType.LoadBalancer]);function l(e,t){return t?.loadBalanced?s.ServerType.LoadBalancer:e&&e.ok?e.isreplicaset?s.ServerType.RSGhost:e.msg&&"isdbgrid"===e.msg?s.ServerType.Mongos:e.setName?e.hidden?s.ServerType.RSOther:e.isWritablePrimary?s.ServerType.RSPrimary:e.secondary?s.ServerType.RSSecondary:e.arbiterOnly?s.ServerType.RSArbiter:s.ServerType.RSOther:s.ServerType.Standalone:s.ServerType.Unknown}function d(e,t){if(null==e||null==t)return-1;if(!e.processId.equals(t.processId))return-1;const o="bigint"==typeof e.counter?n.Long.fromBigInt(e.counter):n.Long.isLong(e.counter)?e.counter:n.Long.fromNumber(e.counter),r="bigint"==typeof t.counter?n.Long.fromBigInt(t.counter):n.Long.isLong(t.counter)?t.counter:n.Long.fromNumber(t.counter);return o.compare(r)}t.ServerDescription=class{constructor(e,t,o={}){if(null==e||""===e)throw new r.MongoRuntimeError("ServerDescription must be provided with a non-empty address");this.address="string"==typeof e?i.HostAddress.fromString(e).toString():e.toString(),this.type=l(t,o),this.hosts=t?.hosts?.map((e=>e.toLowerCase()))??[],this.passives=t?.passives?.map((e=>e.toLowerCase()))??[],this.arbiters=t?.arbiters?.map((e=>e.toLowerCase()))??[],this.tags=t?.tags??{},this.minWireVersion=t?.minWireVersion??0,this.maxWireVersion=t?.maxWireVersion??0,this.roundTripTime=o?.roundTripTime??-1,this.minRoundTripTime=o?.minRoundTripTime??0,this.lastUpdateTime=(0,i.processTimeMS)(),this.lastWriteDate=t?.lastWrite?.lastWriteDate??0,this.error=o.error??null,this.error,this.topologyVersion=this.error?.topologyVersion??t?.topologyVersion??null,this.setName=t?.setName??null,this.setVersion=t?.setVersion??null,this.electionId=t?.electionId??null,this.logicalSessionTimeoutMinutes=t?.logicalSessionTimeoutMinutes??null,this.maxMessageSizeBytes=t?.maxMessageSizeBytes??null,this.maxWriteBatchSize=t?.maxWriteBatchSize??null,this.maxBsonObjectSize=t?.maxBsonObjectSize??null,this.primary=t?.primary??null,this.me=t?.me?.toLowerCase()??null,this.$clusterTime=t?.$clusterTime??null,this.iscryptd=Boolean(t?.iscryptd)}get hostAddress(){return i.HostAddress.fromString(this.address)}get allHosts(){return this.hosts.concat(this.arbiters).concat(this.passives)}get isReadable(){return this.type===s.ServerType.RSSecondary||this.isWritable}get isDataBearing(){return c.has(this.type)}get isWritable(){return a.has(this.type)}get host(){const e=`:${this.port}`.length;return this.address.slice(0,-e)}get port(){const e=this.address.split(":").pop();return e?Number.parseInt(e,10):27017}equals(e){const t=this.topologyVersion===e?.topologyVersion||0===d(this.topologyVersion,e?.topologyVersion),o=null!=this.electionId&&null!=e?.electionId?0===(0,i.compareObjectId)(this.electionId,e.electionId):this.electionId===e?.electionId;return null!=e&&e.iscryptd===this.iscryptd&&(0,i.errorStrictEqual)(this.error,e.error)&&this.type===e.type&&this.minWireVersion===e.minWireVersion&&(0,i.arrayStrictEqual)(this.hosts,e.hosts)&&function(e,t){const o=Object.keys(e),n=Object.keys(t);return o.length===n.length&&o.every((o=>t[o]===e[o]))}(this.tags,e.tags)&&this.setName===e.setName&&this.setVersion===e.setVersion&&o&&this.primary===e.primary&&this.logicalSessionTimeoutMinutes===e.logicalSessionTimeoutMinutes&&t}}},32985:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoCredentials=t.DEFAULT_ALLOWED_HOSTS=void 0;const n=o(36997),r=o(21427),i=o(65070);function s(e){return e&&Array.isArray(e.saslSupportedMechs)?e.saslSupportedMechs.includes(i.AuthMechanism.MONGODB_SCRAM_SHA256)?i.AuthMechanism.MONGODB_SCRAM_SHA256:i.AuthMechanism.MONGODB_SCRAM_SHA1:i.AuthMechanism.MONGODB_SCRAM_SHA256}const a=["test","azure","gcp","k8s"],c="Auth mechanism property ALLOWED_HOSTS must be an array of strings.";t.DEFAULT_ALLOWED_HOSTS=["*.mongodb.net","*.mongodb-qa.net","*.mongodb-dev.net","*.mongodbgov.net","localhost","127.0.0.1","::1","*.mongo.com"];class l{constructor(e){this.username=e.username??"",this.password=e.password,this.source=e.source,!this.source&&e.db&&(this.source=e.db),this.mechanism=e.mechanism||i.AuthMechanism.MONGODB_DEFAULT,this.mechanismProperties=e.mechanismProperties||{},this.mechanism!==i.AuthMechanism.MONGODB_OIDC||this.mechanismProperties.ALLOWED_HOSTS||(this.mechanismProperties={...this.mechanismProperties,ALLOWED_HOSTS:t.DEFAULT_ALLOWED_HOSTS}),Object.freeze(this.mechanismProperties),Object.freeze(this)}equals(e){return this.mechanism===e.mechanism&&this.username===e.username&&this.password===e.password&&this.source===e.source}resolveAuthMechanism(e){return this.mechanism.match(/DEFAULT/i)?new l({username:this.username,password:this.password,source:this.source,mechanism:s(e),mechanismProperties:this.mechanismProperties}):this}validate(){if((this.mechanism===i.AuthMechanism.MONGODB_GSSAPI||this.mechanism===i.AuthMechanism.MONGODB_PLAIN||this.mechanism===i.AuthMechanism.MONGODB_SCRAM_SHA1||this.mechanism===i.AuthMechanism.MONGODB_SCRAM_SHA256)&&!this.username)throw new n.MongoMissingCredentialsError(`Username required for mechanism '${this.mechanism}'`);if(this.mechanism===i.AuthMechanism.MONGODB_OIDC){if(this.username&&this.mechanismProperties.ENVIRONMENT&&"azure"!==this.mechanismProperties.ENVIRONMENT)throw new n.MongoInvalidArgumentError(`username and ENVIRONMENT '${this.mechanismProperties.ENVIRONMENT}' may not be used together for mechanism '${this.mechanism}'.`);if(this.username&&this.password)throw new n.MongoInvalidArgumentError(`No password is allowed in ENVIRONMENT '${this.mechanismProperties.ENVIRONMENT}' for '${this.mechanism}'.`);if(("azure"===this.mechanismProperties.ENVIRONMENT||"gcp"===this.mechanismProperties.ENVIRONMENT)&&!this.mechanismProperties.TOKEN_RESOURCE)throw new n.MongoInvalidArgumentError("TOKEN_RESOURCE must be set in the auth mechanism properties when ENVIRONMENT is azure or gcp.");if(this.mechanismProperties.ENVIRONMENT&&!a.includes(this.mechanismProperties.ENVIRONMENT))throw new n.MongoInvalidArgumentError(`Currently only a ENVIRONMENT in ${a.join(",")} is supported for mechanism '${this.mechanism}'.`);if(!this.mechanismProperties.ENVIRONMENT&&!this.mechanismProperties.OIDC_CALLBACK&&!this.mechanismProperties.OIDC_HUMAN_CALLBACK)throw new n.MongoInvalidArgumentError(`Either a ENVIRONMENT, OIDC_CALLBACK, or OIDC_HUMAN_CALLBACK must be specified for mechanism '${this.mechanism}'.`);if(this.mechanismProperties.ALLOWED_HOSTS){const e=this.mechanismProperties.ALLOWED_HOSTS;if(!Array.isArray(e))throw new n.MongoInvalidArgumentError(c);for(const t of e)if("string"!=typeof t)throw new n.MongoInvalidArgumentError(c)}}if(i.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(this.mechanism)&&null!=this.source&&"$external"!==this.source)throw new n.MongoAPIError(`Invalid source '${this.source}' for mechanism '${this.mechanism}' specified.`);if(this.mechanism===i.AuthMechanism.MONGODB_PLAIN&&null==this.source)throw new n.MongoAPIError("PLAIN Authentication Mechanism needs an auth source");if(this.mechanism===i.AuthMechanism.MONGODB_X509&&null!=this.password){if(""===this.password)return void Reflect.set(this,"password",void 0);throw new n.MongoAPIError("Password not allowed for mechanism MONGODB-X509")}const e=this.mechanismProperties.CANONICALIZE_HOST_NAME??!1;if(!Object.values(r.GSSAPICanonicalizationValue).includes(e))throw new n.MongoAPIError(`Invalid CANONICALIZE_HOST_NAME value: ${e}`)}static merge(e,t){return new l({username:t.username??e?.username??"",password:t.password??e?.password??"",mechanism:t.mechanism??e?.mechanism??i.AuthMechanism.MONGODB_DEFAULT,mechanismProperties:t.mechanismProperties??e?.mechanismProperties??{},source:t.source??t.db??e?.source??"admin"})}}t.MongoCredentials=l},33628:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LegacyTimeoutContext=t.CSOTTimeoutContext=t.TimeoutContext=t.Timeout=t.TimeoutError=void 0;const n=o(31713),r=o(36997),i=o(30306);class s extends Error{get name(){return"TimeoutError"}constructor(e,t){super(e,t),this.duration=t.duration}static is(e){return null!=e&&"object"==typeof e&&"name"in e&&"TimeoutError"===e.name}}t.TimeoutError=s;class a extends Promise{get remainingTime(){return this.timedOut?0:0===this.duration?1/0:this.start+this.duration-Math.trunc(performance.now())}get timeElapsed(){return Math.trunc(performance.now())-this.start}constructor(e=()=>null,t){const o=t?.duration??0,a=!!t?.unref,c=t?.rejection;if(o<0)throw new r.MongoInvalidArgumentError("Cannot create a Timeout with a negative duration");let l;super(((t,o)=>{l=o,e(i.noop,o)})),this.ended=null,this.timedOut=!1,this.cleared=!1,this.duration=o,this.start=Math.trunc(performance.now()),null==c&&this.duration>0?(this.id=(0,n.setTimeout)((()=>{this.ended=Math.trunc(performance.now()),this.timedOut=!0,l(new s(`Expired after ${o}ms`,{duration:o}))}),this.duration),"function"==typeof this.id.unref&&a&&this.id.unref()):null!=c&&(this.ended=Math.trunc(performance.now()),this.timedOut=!0,l(c))}clear(){(0,n.clearTimeout)(this.id),this.id=void 0,this.timedOut=!1,this.cleared=!0}throwIfExpired(){if(this.timedOut)throw this.then(void 0,i.squashError),new s("Timed out",{duration:this.duration})}static expires(e,t){return new a(void 0,{duration:e,unref:t})}static reject(e){return new a(void 0,{duration:0,unref:!0,rejection:e})}}t.Timeout=a;class c{static create(e){if(null!=e.session?.timeoutContext)return e.session?.timeoutContext;if(null!=(t=e)&&"object"==typeof t&&"serverSelectionTimeoutMS"in t&&"number"==typeof t.serverSelectionTimeoutMS&&"timeoutMS"in t&&"number"==typeof t.timeoutMS)return new l(e);if(function(e){return null!=e&&"object"==typeof e&&"serverSelectionTimeoutMS"in e&&"number"==typeof e.serverSelectionTimeoutMS&&"waitQueueTimeoutMS"in e&&"number"==typeof e.waitQueueTimeoutMS}(e))return new d(e);throw new r.MongoRuntimeError("Unrecognized options");var t}}t.TimeoutContext=c;class l extends c{constructor(e){super(),this.minRoundTripTime=0,this.start=Math.trunc(performance.now()),this.timeoutMS=e.timeoutMS,this.serverSelectionTimeoutMS=e.serverSelectionTimeoutMS,this.socketTimeoutMS=e.socketTimeoutMS,this.clearServerSelectionTimeout=!1}get maxTimeMS(){return this.remainingTimeMS-this.minRoundTripTime}get remainingTimeMS(){const e=Math.trunc(performance.now())-this.start;return this.timeoutMS<=0?1/0:this.timeoutMS-e}csotEnabled(){return!0}get serverSelectionTimeout(){if("object"!=typeof this._serverSelectionTimeout||this._serverSelectionTimeout?.cleared){const{remainingTimeMS:e,serverSelectionTimeoutMS:t}=this;if(e<=0)return a.reject(new r.MongoOperationTimeoutError(`Timed out in server selection after ${this.timeoutMS}ms`));0!==t&&(0,i.csotMin)(e,t)===t?this._serverSelectionTimeout=a.expires(t):e>0&&Number.isFinite(e)?this._serverSelectionTimeout=a.expires(e):this._serverSelectionTimeout=null}return this._serverSelectionTimeout}get connectionCheckoutTimeout(){if("object"!=typeof this._connectionCheckoutTimeout||this._connectionCheckoutTimeout?.cleared){if("object"!=typeof this._serverSelectionTimeout)throw new r.MongoRuntimeError("Unreachable. If you are seeing this error, please file a ticket on the NODE driver project on Jira");this._connectionCheckoutTimeout=this._serverSelectionTimeout}return this._connectionCheckoutTimeout}get timeoutForSocketWrite(){const{remainingTimeMS:e}=this;return Number.isFinite(e)?e>0?a.expires(e):a.reject(new r.MongoOperationTimeoutError("Timed out before socket write")):null}get timeoutForSocketRead(){const{remainingTimeMS:e}=this;return Number.isFinite(e)?e>0?a.expires(e):a.reject(new r.MongoOperationTimeoutError("Timed out before socket read")):null}refresh(){this.start=Math.trunc(performance.now()),this.minRoundTripTime=0,this._serverSelectionTimeout?.clear(),this._connectionCheckoutTimeout?.clear()}clear(){this._serverSelectionTimeout?.clear(),this._connectionCheckoutTimeout?.clear()}getRemainingTimeMSOrThrow(e){const{remainingTimeMS:t}=this;if(t<=0)throw new r.MongoOperationTimeoutError(e??`Expired after ${this.timeoutMS}ms`);return t}clone(){const e=new l({timeoutMS:this.timeoutMS,serverSelectionTimeoutMS:this.serverSelectionTimeoutMS});return e.start=this.start,e}refreshed(){return new l(this)}addMaxTimeMSToCommand(e,t){if(t.omitMaxTimeMS)return;const o=this.remainingTimeMS-this.minRoundTripTime;o>0&&Number.isFinite(o)&&(e.maxTimeMS=o)}getSocketTimeoutMS(){return 0}}t.CSOTTimeoutContext=l;class d extends c{constructor(e){super(),this.options=e,this.clearServerSelectionTimeout=!0}csotEnabled(){return!1}get serverSelectionTimeout(){return null!=this.options.serverSelectionTimeoutMS&&this.options.serverSelectionTimeoutMS>0?a.expires(this.options.serverSelectionTimeoutMS):null}get connectionCheckoutTimeout(){return null!=this.options.waitQueueTimeoutMS&&this.options.waitQueueTimeoutMS>0?a.expires(this.options.waitQueueTimeoutMS):null}get timeoutForSocketWrite(){return null}get timeoutForSocketRead(){return null}refresh(){}clear(){}get maxTimeMS(){return null}refreshed(){return new d(this.options)}addMaxTimeMSToCommand(e,t){}getSocketTimeoutMS(){return this.options.socketTimeoutMS}}t.LegacyTimeoutContext=d},34023:function(e,t,o){var n,r=o(15088).process,i=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[t.length]=o);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var o=n(e),r=0;r<o.length;r++)"default"!==o[r]&&i(t,e,o[r]);return s(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.NodeDriverServiceProvider=void 0;const c=o(40818),l=o(92762),d=o(42344),u=o(4580),h=o(13390),m=a(o(183)),p=o(183),g=o(6725),f=o(39446),S=Object.freeze({__skipPingOnConnect:!1}),E=Object.freeze({serializeFunctions:!0,promoteLongs:!1});function y(e,t){const o=e.typedSearchParams(),n=new d.CommaAndColonSeparatedRecord(o.get("authMechanismProperties"));return[e.protocol,e.hosts,t.auth?.username??e.username,t.auth?.password??e.password,t.authMechanism??o.get("authMechanism"),t.authSource??o.get("authSource"),{...Object.fromEntries(n),...t.authMechanismProperties}]}class b extends c.ServiceProviderCore{static async connect(e,t,o={},n=new u.EventEmitter){const i=new d.ConnectionString(e||"mongodb://nodb/"),s=this.processDriverOptions(null,i,t);let a,c,l;if(r.env.MONGOSH_TEST_FORCE_API_STRICT&&(s.serverApi={version:"string"==typeof s.serverApi?s.serverApi:s.serverApi?.version??"1",strict:!0,deprecationErrors:!0}),o.nodb){const e={...s};delete e.productName,delete e.productDocsLink,delete e.oidc,delete e.parentHandle,delete e.parentState,delete e.proxy,delete e.applyProxyToOIDC,a=new p.MongoClient(i.toString(),e)}else({client:a,state:c,lastSeenTopology:l}=await this.connectMongoClient(i.toString(),s,n));return s.parentState=c,new this(a,n,s,i,l)}constructor(e,t,o,n,r){super((()=>{const{Binary:e,Code:t,DBRef:o,Double:n,Int32:r,Long:i,MinKey:s,MaxKey:a,ObjectId:c,Timestamp:l,Decimal128:d,BSONSymbol:u,BSONRegExp:h,UUID:p,BSON:g}=m;return{Binary:e,Code:t,DBRef:o,Double:n,Int32:r,Long:i,MinKey:s,MaxKey:a,ObjectId:c,Timestamp:l,Decimal128:d,BSONSymbol:u,calculateObjectSize:g.calculateObjectSize,EJSON:g.EJSON,UUID:p,BSONRegExp:h}})()),this.bus=t,this.mongoClient=e,this.uri=n,this._lastSeenTopology=r,this.platform="CLI";try{this.initialDb=e.options.dbName||c.DEFAULT_DB}catch(e){this.initialDb=c.DEFAULT_DB}this.currentClientOptions=o,this.baseCmdOptions={...E},this.dbcache=new WeakMap,this.mongoClient.on?.("topologyDescriptionChanged",(e=>{this._lastSeenTopology=e.newDescription}))}static getVersionInformation(){return{nodeDriverVersion:(()=>{try{return o(46195).rE}catch{return}})(),libmongocryptVersion:(()=>{try{return p.ClientEncryption.libmongocryptVersion}catch{return}})(),libmongocryptNodeBindingsVersion:(()=>{try{return o(64113).version}catch{return}})(),kerberosVersion:(()=>{try{return o(64113).version}catch{return}})()}}static maybeThrowBetterMissingOptionalDependencyError(e){if(e.message.includes("kerberos"))try{o(64113)}catch(e){if("object"==typeof e&&e&&"message"in e&&"string"==typeof e.message)throw new Error(`Could not load kerberos package: ${e.message}`,{cause:e})}if(e.message.includes("mongodb-client-encryption"))try{o(64113)}catch(e){if("object"==typeof e&&e&&"message"in e&&"string"==typeof e.message){const t="boxednode"in r?"":"\n(If you are installing mongosh through homebrew or npm, consider downlading mongosh from https://www.mongodb.com/try/download/shell instead)";throw new Error(`Could not load mongodb-client-encryption package: ${e.message}${t}`,{cause:e})}}throw e}static async connectMongoClient(e,t,o){let n;class r extends p.MongoClient{constructor(e,t){super(e,t),this.on("topologyDescriptionChanged",(e=>{n=e.newDescription}))}}try{return{...await(0,g.connectMongoClient)(e.toString(),t,o,r),lastSeenTopology:n}}catch(e){throw"object"==typeof e&&e&&"name"in e&&"MongoMissingDependencyError"===e.name&&this.maybeThrowBetterMissingOptionalDependencyError(e),e}}async getNewConnection(e,t={}){const o=new d.ConnectionString(e),n=this.processDriverOptions(o,t),{client:r,state:i,lastSeenTopology:s}=await b.connectMongoClient(o.toString(),n,this.bus);return n.parentState=i,new b(r,this.bus,n,o,s??this._lastSeenTopology)}_getHostnameForConnection(e){return e?.servers?.values().next().value?.hostAddress.host}async getConnectionInfo(){const e=this.runCommandWithCheck("admin",{buildInfo:1},this.baseCmdOptions).catch((()=>({}))),[t,o=null,n=null,r,i]=await Promise.all([e,this.runCommandWithCheck("admin",{atlasVersion:1},this.baseCmdOptions).catch((()=>{})),this.runCommandWithCheck("admin",{getParameter:1,featureCompatibilityVersion:1},this.baseCmdOptions).catch((()=>{})),this.countDocuments("admin","atlascli",{managedClusterType:"atlasCliLocalDevCluster"}).catch((()=>0)),(0,f.identifyServerName)({connectionString:this.uri?.toString()??"",adminCommand:t=>t.buildInfo?e:this.runCommandWithCheck("admin",t,this.baseCmdOptions)})]),s=this._getHostnameForConnection(this._lastSeenTopology);return{buildInfo:t,resolvedHostname:s,extraInfo:{...(0,c.getConnectExtraInfo)({connectionString:this.uri,buildInfo:t,atlasVersion:o,resolvedHostname:s,isLocalAtlas:!!r,serverName:i}),fcv:n?.featureCompatibilityVersion?.version}}}async renameCollection(e,t,o,n={},r){return n={...this.baseCmdOptions,...n},await this.db(e,r).renameCollection(t,o,n)}db(e,t={}){const o=`${e}-${JSON.stringify(t)}`,n=this.getDBCache(),r=n.get(o);if(r)return r;const i=this.mongoClient.db(e,t);return n.set(o,i),i}_dbTestWrapper(e,t){return this.db(e,t)}getDBCache(){return this.dbcache.get(this.mongoClient)||(this.dbcache.set(this.mongoClient,new Map),this.getDBCache())}hasUnifiedAggregateOptions(){return!0}aggregate(e,t,o=[],n={},r){return n={...this.baseCmdOptions,...n},this.db(e,r).collection(t).aggregate(o,n)}aggregateDb(e,t=[],o={},n){return o={...this.baseCmdOptions,...o},this.db(e,n).aggregate(t,o)}bulkWrite(e,t,o,n={},r){return n={...this.baseCmdOptions,...n},this.db(e,r).collection(t).bulkWrite(o,n)}clientBulkWrite(e,t={}){return t={...this.baseCmdOptions,...t},this.mongoClient.bulkWrite(e,t)}async close(){this.dbcache.set(this.mongoClient,new Map),await this.mongoClient.close()}async suspend(){return await this.close(),async()=>{await this.resetConnectionOptions({})}}count(e,t,o={},n={},r){return n={...this.baseCmdOptions,...n},this.db(e,r).collection(t).count(o,n)}countDocuments(e,t,o={},n={},r){return n={...this.baseCmdOptions,...n},this.db(e,r).collection(t).countDocuments(o,n)}deleteMany(e,t,o={},n={},r){return n={...this.baseCmdOptions,...n},this.db(e,r).collection(t).deleteMany(o,n)}deleteOne(e,t,o={},n={},r){return n={...this.baseCmdOptions,...n},this.db(e,r).collection(t).deleteOne(o,n)}distinct(e,t,o,n={},r={},i){return r={...this.baseCmdOptions,...r},this.db(e,i).collection(t).distinct(o,n,r)}estimatedDocumentCount(e,t,o={},n){return o={...this.baseCmdOptions,...o},this.db(e,n).collection(t).estimatedDocumentCount(o)}find(e,t,o={},n={},r){const i={...this.baseCmdOptions,...n};return"allowPartialResults"in i&&(i.partial=i.allowPartialResults),"noCursorTimeout"in i&&(i.timeout=i.noCursorTimeout),this.db(e,r).collection(t).find(o,i)}findOneAndDelete(e,t,o={},n={},r){return n={includeResultMetadata:!0,...this.baseCmdOptions,...n},this.db(e,r).collection(t).findOneAndDelete(o,n)}findOneAndReplace(e,t,o={},n={},r={},i){const s={includeResultMetadata:!0,...this.baseCmdOptions,...r};return this.db(e,i).collection(t).findOneAndReplace(o,n,s)}findOneAndUpdate(e,t,o={},n={},r={},i){const s={includeResultMetadata:!0,...this.baseCmdOptions,...r};return this.db(e,i).collection(t).findOneAndUpdate(o,n,s)}insertMany(e,t,o=[],n={},r){return n={...this.baseCmdOptions,...n},this.db(e,r).collection(t).insertMany(o,n)}async insertOne(e,t,o={},n={},r){return n={...this.baseCmdOptions,...n},this.db(e,r).collection(t).insertOne(o,n)}replaceOne(e,t,o={},n={},r={},i){return r={...this.baseCmdOptions,...r},this.db(e,i).collection(t).replaceOne(o,n,r)}runCommand(e,t={},o={},n){return o={...this.baseCmdOptions,...o},this.db(e,n).command(t,o)}async runCommandWithCheck(e,t={},o={},n){const r=await this.runCommand(e,t,o,n);if(0===r.ok)throw new l.MongoshCommandFailed(JSON.stringify(t));return r}runCursorCommand(e,t={},o={},n){return o={...this.baseCmdOptions,...o},this.db(e,n).runCursorCommand(t,o)}listDatabases(e,t={}){return t={...this.baseCmdOptions,...t},this.db(e).admin().listDatabases(t)}async updateMany(e,t,o={},n={},r={},i){return r={...this.baseCmdOptions,...r},await this.db(e,i).collection(t).updateMany(o,n,r)}updateOne(e,t,o={},n={},r={},i){return r={...this.baseCmdOptions,...r},this.db(e,i).collection(t).updateOne(o,n,r)}getTopologyDescription(){return this._lastSeenTopology}async dropDatabase(e,t={},o={}){const n={...this.baseCmdOptions,...t},r=await this.db(e,o).dropDatabase(n)?1:0;return{ok:r,...r?{dropped:e}:{}}}async createIndexes(e,t,o,n={},r){return n={...this.baseCmdOptions,...n},this.db(e,r).collection(t).createIndexes(o,n)}async getIndexes(e,t,o={},n){return await this.db(e,n).collection(t).listIndexes({...this.baseCmdOptions,...o}).toArray()}async listCollections(e,t={},o={},n){return o={...this.baseCmdOptions,...o},await this.db(e,n).listCollections(t,o).toArray()}async dropCollection(e,t,o={},n){return this.db(e,n).collection(t).drop({...this.baseCmdOptions,...o})}async authenticate(e){const t={username:e.user,password:e.pwd};return await this.resetConnectionOptions({auth:t,...e.mechanism?{authMechanism:e.mechanism}:{},...e.authDb?{authSource:e.authDb}:{}}),{ok:1}}async createCollection(e,t,o={},n){return o={...this.baseCmdOptions,...o},await this.db(e,n).createCollection(t,o),{ok:1}}async createEncryptedCollection(e,t,o,n){return await n.createEncryptedCollection(this.db(e),t,o)}async initializeBulkOp(e,t,o,n={},r){return o?this.db(e,r).collection(t).initializeOrderedBulkOp(n):this.db(e,r).collection(t).initializeUnorderedBulkOp(n)}getReadPreference(){return this.mongoClient.readPreference}getReadConcern(){return this.mongoClient.readConcern}getWriteConcern(){return this.mongoClient.writeConcern}readPreferenceFromOptions(e){return p.ReadPreference.fromOptions(e)}async resetConnectionOptions(e){this.bus.emit("mongosh-sp:reset-connection-options"),this.currentClientOptions={...this.currentClientOptions,...e};const t=this.processDriverOptions(this.uri,this.currentClientOptions),{client:o,state:n,lastSeenTopology:r}=await b.connectMongoClient(this.uri.toString(),t,this.bus);try{await this.mongoClient.close()}catch{}this.mongoClient=o,this.currentClientOptions.parentState=n,r&&(this._lastSeenTopology=r)}startSession(e){return this.mongoClient.startSession(e)}watch(e,t,o={},n,r){if(void 0===n&&void 0===r)return this.mongoClient.watch(e,t);if(void 0!==n&&void 0===r)return this.db(n,o).watch(e,t);if(void 0!==n&&void 0!==r)return this.db(n,o).collection(r).watch(e,t);throw new l.MongoshInternalError("Cannot call watch with defined collection but undefined db")}getRawClient(){return this.mongoClient}getURI(){return this.uri?.href}getFleOptions(){return this.currentClientOptions.autoEncryption}static processDriverOptions(e,t,o){const n={...S,...o};if(e?.currentClientOptions){for(const t of["productName","productDocsLink"])n[t]=e.currentClientOptions[t];n.oidc??={};for(const t of["redirectURI","openBrowser","openBrowserTimeout","notifyDeviceFlow","allowedFlows"])(t=>{const o=e.currentClientOptions.oidc?.[t];o&&(n.oidc[t]=o)})(t)}if(n.parentState||n.parentHandle||!e)return n;const r=e.currentClientOptions,i=e.uri;return i&&(0,h.isDeepStrictEqual)(y(i,r),y(t,n))&&(r.parentState?n.parentState=r.parentState:r.parentHandle&&(n.parentHandle=r.parentHandle)),n}processDriverOptions(e,t){return b.processDriverOptions(this,e,{productName:this.currentClientOptions.productName,productDocsLink:this.currentClientOptions.productDocsLink,...t})}getSearchIndexes(e,t,o,n,r){const i=this.db(e,r).collection(t);return void 0===o?i.listSearchIndexes(n).toArray():i.listSearchIndexes(o,n).toArray()}createSearchIndexes(e,t,o,n){return this.db(e,n).collection(t).createSearchIndexes(o)}dropSearchIndex(e,t,o,n){return this.db(e,n).collection(t).dropSearchIndex(o)}updateSearchIndex(e,t,o,n,r){return this.db(e,r).collection(t).updateSearchIndex(o,n)}createClientEncryption(e){return new p.ClientEncryption(this.mongoClient,e)}}t.NodeDriverServiceProvider=b},34037:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bsonType=void 0,t.getBsonType=function(e){return e?.[n.bsonType]};const n=o(13353);Object.defineProperty(t,"bsonType",{enumerable:!0,get:function(){return n.bsonType}})},34842:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.END=t.CHANGE=t.INIT=t.MORE=t.RESPONSE=t.SERVER_HEARTBEAT_FAILED=t.SERVER_HEARTBEAT_SUCCEEDED=t.SERVER_HEARTBEAT_STARTED=t.COMMAND_FAILED=t.COMMAND_SUCCEEDED=t.COMMAND_STARTED=t.CLUSTER_TIME_RECEIVED=t.CONNECTION_CHECKED_IN=t.CONNECTION_CHECKED_OUT=t.CONNECTION_CHECK_OUT_FAILED=t.CONNECTION_CHECK_OUT_STARTED=t.CONNECTION_CLOSED=t.CONNECTION_READY=t.CONNECTION_CREATED=t.CONNECTION_POOL_READY=t.CONNECTION_POOL_CLEARED=t.CONNECTION_POOL_CLOSED=t.CONNECTION_POOL_CREATED=t.WAITING_FOR_SUITABLE_SERVER=t.SERVER_SELECTION_SUCCEEDED=t.SERVER_SELECTION_FAILED=t.SERVER_SELECTION_STARTED=t.TOPOLOGY_DESCRIPTION_CHANGED=t.TOPOLOGY_CLOSED=t.TOPOLOGY_OPENING=t.SERVER_DESCRIPTION_CHANGED=t.SERVER_CLOSED=t.SERVER_OPENING=t.DESCRIPTION_RECEIVED=t.UNPINNED=t.PINNED=t.MESSAGE=t.ENDED=t.CLOSED=t.CONNECT=t.OPEN=t.CLOSE=t.TIMEOUT=t.ERROR=t.SYSTEM_JS_COLLECTION=t.SYSTEM_COMMAND_COLLECTION=t.SYSTEM_USER_COLLECTION=t.SYSTEM_PROFILE_COLLECTION=t.SYSTEM_INDEX_COLLECTION=t.SYSTEM_NAMESPACE_COLLECTION=void 0,t.kDecoratedKeys=t.kDecorateResult=t.LEGACY_HELLO_COMMAND_CAMEL_CASE=t.LEGACY_HELLO_COMMAND=t.MONGO_CLIENT_EVENTS=t.LOCAL_SERVER_EVENTS=t.SERVER_RELAY_EVENTS=t.APM_EVENTS=t.TOPOLOGY_EVENTS=t.CMAP_EVENTS=t.HEARTBEAT_EVENTS=t.RESUME_TOKEN_CHANGED=void 0,t.SYSTEM_NAMESPACE_COLLECTION="system.namespaces",t.SYSTEM_INDEX_COLLECTION="system.indexes",t.SYSTEM_PROFILE_COLLECTION="system.profile",t.SYSTEM_USER_COLLECTION="system.users",t.SYSTEM_COMMAND_COLLECTION="$cmd",t.SYSTEM_JS_COLLECTION="system.js",t.ERROR="error",t.TIMEOUT="timeout",t.CLOSE="close",t.OPEN="open",t.CONNECT="connect",t.CLOSED="closed",t.ENDED="ended",t.MESSAGE="message",t.PINNED="pinned",t.UNPINNED="unpinned",t.DESCRIPTION_RECEIVED="descriptionReceived",t.SERVER_OPENING="serverOpening",t.SERVER_CLOSED="serverClosed",t.SERVER_DESCRIPTION_CHANGED="serverDescriptionChanged",t.TOPOLOGY_OPENING="topologyOpening",t.TOPOLOGY_CLOSED="topologyClosed",t.TOPOLOGY_DESCRIPTION_CHANGED="topologyDescriptionChanged",t.SERVER_SELECTION_STARTED="serverSelectionStarted",t.SERVER_SELECTION_FAILED="serverSelectionFailed",t.SERVER_SELECTION_SUCCEEDED="serverSelectionSucceeded",t.WAITING_FOR_SUITABLE_SERVER="waitingForSuitableServer",t.CONNECTION_POOL_CREATED="connectionPoolCreated",t.CONNECTION_POOL_CLOSED="connectionPoolClosed",t.CONNECTION_POOL_CLEARED="connectionPoolCleared",t.CONNECTION_POOL_READY="connectionPoolReady",t.CONNECTION_CREATED="connectionCreated",t.CONNECTION_READY="connectionReady",t.CONNECTION_CLOSED="connectionClosed",t.CONNECTION_CHECK_OUT_STARTED="connectionCheckOutStarted",t.CONNECTION_CHECK_OUT_FAILED="connectionCheckOutFailed",t.CONNECTION_CHECKED_OUT="connectionCheckedOut",t.CONNECTION_CHECKED_IN="connectionCheckedIn",t.CLUSTER_TIME_RECEIVED="clusterTimeReceived",t.COMMAND_STARTED="commandStarted",t.COMMAND_SUCCEEDED="commandSucceeded",t.COMMAND_FAILED="commandFailed",t.SERVER_HEARTBEAT_STARTED="serverHeartbeatStarted",t.SERVER_HEARTBEAT_SUCCEEDED="serverHeartbeatSucceeded",t.SERVER_HEARTBEAT_FAILED="serverHeartbeatFailed",t.RESPONSE="response",t.MORE="more",t.INIT="init",t.CHANGE="change",t.END="end",t.RESUME_TOKEN_CHANGED="resumeTokenChanged",t.HEARTBEAT_EVENTS=Object.freeze([t.SERVER_HEARTBEAT_STARTED,t.SERVER_HEARTBEAT_SUCCEEDED,t.SERVER_HEARTBEAT_FAILED]),t.CMAP_EVENTS=Object.freeze([t.CONNECTION_POOL_CREATED,t.CONNECTION_POOL_READY,t.CONNECTION_POOL_CLEARED,t.CONNECTION_POOL_CLOSED,t.CONNECTION_CREATED,t.CONNECTION_READY,t.CONNECTION_CLOSED,t.CONNECTION_CHECK_OUT_STARTED,t.CONNECTION_CHECK_OUT_FAILED,t.CONNECTION_CHECKED_OUT,t.CONNECTION_CHECKED_IN]),t.TOPOLOGY_EVENTS=Object.freeze([t.SERVER_OPENING,t.SERVER_CLOSED,t.SERVER_DESCRIPTION_CHANGED,t.TOPOLOGY_OPENING,t.TOPOLOGY_CLOSED,t.TOPOLOGY_DESCRIPTION_CHANGED,t.ERROR,t.TIMEOUT,t.CLOSE]),t.APM_EVENTS=Object.freeze([t.COMMAND_STARTED,t.COMMAND_SUCCEEDED,t.COMMAND_FAILED]),t.SERVER_RELAY_EVENTS=Object.freeze([t.SERVER_HEARTBEAT_STARTED,t.SERVER_HEARTBEAT_SUCCEEDED,t.SERVER_HEARTBEAT_FAILED,t.COMMAND_STARTED,t.COMMAND_SUCCEEDED,t.COMMAND_FAILED,...t.CMAP_EVENTS]),t.LOCAL_SERVER_EVENTS=Object.freeze([t.CONNECT,t.DESCRIPTION_RECEIVED,t.CLOSED,t.ENDED]),t.MONGO_CLIENT_EVENTS=Object.freeze([...t.CMAP_EVENTS,...t.APM_EVENTS,...t.TOPOLOGY_EVENTS,...t.HEARTBEAT_EVENTS]),t.LEGACY_HELLO_COMMAND="ismaster",t.LEGACY_HELLO_COMMAND_CAMEL_CASE="isMaster",t.kDecorateResult=Symbol.for("@@mdb.decorateDecryptionResult"),t.kDecoratedKeys=Symbol.for("@@mdb.decryptedKeys")},36667:(e,t,o)=>{var n=o(34110).Buffer;if(Object.defineProperty(t,"__esModule",{value:!0}),t.textEncodingPolyfill=r,"function"!=typeof TextDecoder||"function"!=typeof TextEncoder){const e="object"==typeof globalThis&&globalThis?.Object===Object&&globalThis||Function("return this")();Object.assign(e,r())}function r(){return{TextDecoder:class{decode(e){const t=n.from(e).toString("utf8");return t.slice(+t.startsWith("\ufeff"))}},TextEncoder:class{encode(e){return n.from(e,"utf8")}}}}},36964:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Topology=void 0;const n=o(52859),r=o(34842),i=o(36997),s=o(60866),a=o(72361),c=o(74891),l=o(33628),d=o(30306),u=o(90648),h=o(86348),m=o(89678),p=o(32583),g=o(26119),f=o(61347),S=o(39272),E=o(79573);let y=0;const b=(0,d.makeStateMachine)({[u.STATE_CLOSED]:[u.STATE_CLOSED,u.STATE_CONNECTING],[u.STATE_CONNECTING]:[u.STATE_CONNECTING,u.STATE_CLOSING,u.STATE_CONNECTED,u.STATE_CLOSED],[u.STATE_CONNECTED]:[u.STATE_CONNECTED,u.STATE_CLOSING,u.STATE_CLOSED],[u.STATE_CLOSING]:[u.STATE_CLOSING,u.STATE_CLOSED]});class O extends a.TypedEventEmitter{static{this.SERVER_OPENING=r.SERVER_OPENING}static{this.SERVER_CLOSED=r.SERVER_CLOSED}static{this.SERVER_DESCRIPTION_CHANGED=r.SERVER_DESCRIPTION_CHANGED}static{this.TOPOLOGY_OPENING=r.TOPOLOGY_OPENING}static{this.TOPOLOGY_CLOSED=r.TOPOLOGY_CLOSED}static{this.TOPOLOGY_DESCRIPTION_CHANGED=r.TOPOLOGY_DESCRIPTION_CHANGED}static{this.ERROR=r.ERROR}static{this.OPEN=r.OPEN}static{this.CONNECT=r.CONNECT}static{this.CLOSE=r.CLOSE}static{this.TIMEOUT=r.TIMEOUT}constructor(e,t,o){super(),this.on("error",d.noop),this.client=e,o=o??{hosts:[d.HostAddress.fromString("localhost:27017")],...Object.fromEntries(n.DEFAULT_OPTIONS.entries())},"string"==typeof t?t=[d.HostAddress.fromString(t)]:Array.isArray(t)||(t=[t]);const r=[];for(const e of t)if("string"==typeof e)r.push(d.HostAddress.fromString(e));else{if(!(e instanceof d.HostAddress))throw new i.MongoRuntimeError(`Topology cannot be constructed from ${JSON.stringify(e)}`);r.push(e)}const s=function(e){return e?.directConnection?u.TopologyType.Single:e?.replicaSet?u.TopologyType.ReplicaSetNoPrimary:e?.loadBalanced?u.TopologyType.LoadBalanced:u.TopologyType.Unknown}(o),a=y++,c=null==o.srvMaxHosts||0===o.srvMaxHosts||o.srvMaxHosts>=r.length?r:(0,d.shuffle)(r,o.srvMaxHosts),l=new Map;for(const e of c)l.set(e.toString(),new p.ServerDescription(e));this.waitQueue=new d.List,this.s={id:a,options:o,seedlist:r,state:u.STATE_CLOSED,description:new E.TopologyDescription(s,l,o.replicaSet,void 0,void 0,void 0,o),serverSelectionTimeoutMS:o.serverSelectionTimeoutMS,heartbeatFrequencyMS:o.heartbeatFrequencyMS,minHeartbeatFrequencyMS:o.minHeartbeatFrequencyMS,servers:new Map,credentials:o?.credentials,clusterTime:void 0,detectShardedTopology:e=>this.detectShardedTopology(e),detectSrvRecords:e=>this.detectSrvRecords(e)},this.mongoLogger=e.mongoLogger,this.component="topology",o.srvHost&&!o.loadBalanced&&(this.s.srvPoller=o.srvPoller??new S.SrvPoller({heartbeatFrequencyMS:this.s.heartbeatFrequencyMS,srvHost:o.srvHost,srvMaxHosts:o.srvMaxHosts,srvServiceName:o.srvServiceName}),this.on(O.TOPOLOGY_DESCRIPTION_CHANGED,this.s.detectShardedTopology)),this.connectionLock=void 0}detectShardedTopology(e){const t=e.previousDescription.type,o=e.newDescription.type,n=t!==u.TopologyType.Sharded&&o===u.TopologyType.Sharded,r=this.s.srvPoller?.listeners(S.SrvPoller.SRV_RECORD_DISCOVERY),i=!!r?.includes(this.s.detectSrvRecords);n&&!i&&(this.s.srvPoller?.on(S.SrvPoller.SRV_RECORD_DISCOVERY,this.s.detectSrvRecords),this.s.srvPoller?.start())}detectSrvRecords(e){const t=this.s.description;this.s.description=this.s.description.updateFromSrvPollingEvent(e,this.s.options.srvMaxHosts),this.s.description!==t&&(T(this),this.emitAndLog(O.TOPOLOGY_DESCRIPTION_CHANGED,new h.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description)))}get description(){return this.s.description}get loadBalanced(){return this.s.options.loadBalanced}get serverApi(){return this.s.options.serverApi}async connect(e){this.connectionLock??=this._connect(e);try{return await this.connectionLock,this}finally{this.connectionLock=void 0}}async _connect(e){if(e=e??{},this.s.state===u.STATE_CONNECTED)return this;b(this,u.STATE_CONNECTING),this.emitAndLog(O.TOPOLOGY_OPENING,new h.TopologyOpeningEvent(this.s.id)),this.emitAndLog(O.TOPOLOGY_DESCRIPTION_CHANGED,new h.TopologyDescriptionChangedEvent(this.s.id,new E.TopologyDescription(u.TopologyType.Unknown),this.s.description));const t=Array.from(this.s.description.servers.values());if(this.s.servers=new Map(t.map((e=>[e.address,M(this,e)]))),this.s.options.loadBalanced)for(const e of t){const t=new p.ServerDescription(e.hostAddress,void 0,{loadBalanced:this.s.options.loadBalanced});this.serverUpdateHandler(t)}const o=this.client.s.options.serverSelectionTimeoutMS,n=e.readPreference??c.ReadPreference.primary,r=l.TimeoutContext.create({timeoutMS:void 0,serverSelectionTimeoutMS:o,waitQueueTimeoutMS:this.client.s.options.waitQueueTimeoutMS}),i={operationName:"handshake",...e,timeoutContext:r,deprioritizedServers:new g.DeprioritizedServers};try{const e=await this.selectServer((0,g.readPreferenceServerSelector)(n),i);if(!0!==this.s.options.__skipPingOnConnect){const t=await e.pool.checkOut({timeoutContext:r});return e.pool.checkIn(t),b(this,u.STATE_CONNECTED),this.emit(O.OPEN,this),this.emit(O.CONNECT,this),this}return b(this,u.STATE_CONNECTED),this.emit(O.OPEN,this),this.emit(O.CONNECT,this),this}catch(e){throw this.close(),e}}closeCheckedOutConnections(){for(const e of this.s.servers.values())return e.closeCheckedOutConnections()}close(){if(this.s.state!==u.STATE_CLOSED&&this.s.state!==u.STATE_CLOSING){for(const e of this.s.servers.values())C(e,this);this.s.servers.clear(),b(this,u.STATE_CLOSING),w(this.waitQueue,new i.MongoTopologyClosedError),this.s.srvPoller&&(this.s.srvPoller.stop(),this.s.srvPoller.removeListener(S.SrvPoller.SRV_RECORD_DISCOVERY,this.s.detectSrvRecords)),this.removeListener(O.TOPOLOGY_DESCRIPTION_CHANGED,this.s.detectShardedTopology),b(this,u.STATE_CLOSED),this.emitAndLog(O.TOPOLOGY_CLOSED,new h.TopologyClosedEvent(this.s.id))}}async selectServer(e,t){let o,n;if("function"!=typeof e)if("string"==typeof e)o=(0,g.readPreferenceServerSelector)(c.ReadPreference.fromString(e));else{let n;e instanceof c.ReadPreference?n=e:(c.ReadPreference.translate(t),n=t.readPreference||c.ReadPreference.primary),o=(0,g.readPreferenceServerSelector)(n)}else o=e;t={serverSelectionTimeoutMS:this.s.serverSelectionTimeoutMS,...t},this.client.mongoLogger?.willLog(s.MongoLoggableComponent.SERVER_SELECTION,s.SeverityLevel.DEBUG)&&this.client.mongoLogger?.debug(s.MongoLoggableComponent.SERVER_SELECTION,new f.ServerSelectionStartedEvent(e,this.description,t.operationName)),n=t.timeoutContext?t.timeoutContext.serverSelectionTimeout:l.Timeout.expires(t.serverSelectionTimeoutMS??0);const r=this.description.type===u.TopologyType.Sharded,a=t.session,h=a&&a.transaction;if(r&&h&&h.server)return this.client.mongoLogger?.willLog(s.MongoLoggableComponent.SERVER_SELECTION,s.SeverityLevel.DEBUG)&&this.client.mongoLogger?.debug(s.MongoLoggableComponent.SERVER_SELECTION,new f.ServerSelectionSucceededEvent(e,this.description,h.server.pool.address,t.operationName)),t.timeoutContext?.clearServerSelectionTimeout&&n?.clear(),h.server;const{promise:m,resolve:p,reject:S}=(0,d.promiseWithResolvers)(),E={serverSelector:o,topologyDescription:this.description,mongoLogger:this.client.mongoLogger,transaction:h,resolve:p,reject:S,cancelled:!1,startTime:(0,d.processTimeMS)(),operationName:t.operationName,waitingLogged:!1,deprioritizedServers:t.deprioritizedServers},y=(0,d.addAbortListener)(t.signal,(function(){E.cancelled=!0,S(this.reason)}));this.waitQueue.push(E),v(this);try{n?.throwIfExpired();const e=await(n?Promise.race([m,n]):m);return t.timeoutContext?.csotEnabled()&&0!==e.description.minRoundTripTime&&(t.timeoutContext.minRoundTripTime=e.description.minRoundTripTime),e}catch(o){if(l.TimeoutError.is(o)){E.cancelled=!0;const o=new i.MongoServerSelectionError(`Server selection timed out after ${n?.duration} ms`,this.description);if(this.client.mongoLogger?.willLog(s.MongoLoggableComponent.SERVER_SELECTION,s.SeverityLevel.DEBUG)&&this.client.mongoLogger?.debug(s.MongoLoggableComponent.SERVER_SELECTION,new f.ServerSelectionFailedEvent(e,this.description,o,t.operationName)),t.timeoutContext?.csotEnabled())throw new i.MongoOperationTimeoutError("Timed out during server selection",{cause:o});throw o}throw o}finally{y?.[d.kDispose](),t.timeoutContext?.clearServerSelectionTimeout&&n?.clear()}}serverUpdateHandler(e){if(!this.s.description.hasServer(e.address))return;if(function(e,t){const o=e.servers.get(t.address),n=o?.topologyVersion;return(0,p.compareTopologyVersion)(n,t.topologyVersion)>0}(this.s.description,e))return;const t=this.s.description,o=this.s.description.servers.get(e.address);if(!o)return;const n=e.$clusterTime;n&&(0,u._advanceClusterTime)(this,n);const r=o&&o.equals(e);if(this.s.description=this.s.description.update(e),this.s.description.compatibilityError)this.emit(O.ERROR,new i.MongoCompatibilityError(this.s.description.compatibilityError));else{if(!r){const t=this.s.description.servers.get(e.address);t&&this.emit(O.SERVER_DESCRIPTION_CHANGED,new h.ServerDescriptionChangedEvent(this.s.id,e.address,o,t))}T(this,e),this.waitQueue.length>0&&v(this),r||this.emitAndLog(O.TOPOLOGY_DESCRIPTION_CHANGED,new h.TopologyDescriptionChangedEvent(this.s.id,t,this.s.description))}}auth(e,t){"function"==typeof e&&(t=e,e=void 0),"function"==typeof t&&t(void 0,!0)}isConnected(){return this.s.state===u.STATE_CONNECTED}isDestroyed(){return this.s.state===u.STATE_CLOSED}lastHello(){const e=Array.from(this.description.servers.values());return 0===e.length?{}:e.filter((e=>e.type!==u.ServerType.Unknown))[0]||{maxWireVersion:this.description.commonWireVersion}}get commonWireVersion(){return this.description.commonWireVersion}get logicalSessionTimeoutMinutes(){return this.description.logicalSessionTimeoutMinutes}get clusterTime(){return this.s.clusterTime}set clusterTime(e){this.s.clusterTime=e}}function C(e,t){for(const t of r.LOCAL_SERVER_EVENTS)e.removeAllListeners(t);e.close(),t.emitAndLog(O.SERVER_CLOSED,new h.ServerClosedEvent(t.s.id,e.description.address));for(const t of r.SERVER_RELAY_EVENTS)e.removeAllListeners(t)}function M(e,t){e.emitAndLog(O.SERVER_OPENING,new h.ServerOpeningEvent(e.s.id,t.address));const o=new m.Server(e,t,e.s.options);for(const t of r.SERVER_RELAY_EVENTS)o.on(t,(o=>e.emit(t,o)));return o.on(m.Server.DESCRIPTION_RECEIVED,(t=>e.serverUpdateHandler(t))),o.connect(),o}function T(e,t){if(t&&e.s.servers.has(t.address)){const o=e.s.servers.get(t.address);if(o)if(o.s.description=t,t.error instanceof i.MongoError&&t.error.hasErrorLabel(i.MongoErrorLabel.ResetPool)){const e=t.error.hasErrorLabel(i.MongoErrorLabel.InterruptInUseConnections);o.pool.clear({interruptInUseConnections:e})}else if(null==t.error){const n=e.s.description.type;(t.isDataBearing||t.type!==u.ServerType.Unknown&&n===u.TopologyType.Single)&&o.pool.ready()}}for(const t of e.description.servers.values())if(!e.s.servers.has(t.address)){const o=M(e,t);e.s.servers.set(t.address,o)}for(const t of e.s.servers){const o=t[0];if(e.description.hasServer(o))continue;if(!e.s.servers.has(o))continue;const n=e.s.servers.get(o);e.s.servers.delete(o),n&&C(n,e)}}function w(e,t){for(;e.length;){const o=e.shift();o&&(o.cancelled||(o.mongoLogger?.willLog(s.MongoLoggableComponent.SERVER_SELECTION,s.SeverityLevel.DEBUG)&&o.mongoLogger?.debug(s.MongoLoggableComponent.SERVER_SELECTION,new f.ServerSelectionFailedEvent(o.serverSelector,o.topologyDescription,t,o.operationName)),o.reject(t)))}}function v(e){if(e.s.state===u.STATE_CLOSED)return void w(e.waitQueue,new i.MongoTopologyClosedError);const t=e.description.type===u.TopologyType.Sharded,o=Array.from(e.description.servers.values()),n=e.waitQueue.length;for(let r=0;r<n;++r){const n=e.waitQueue.shift();if(!n)continue;if(n.cancelled)continue;let r,a;try{const t=n.serverSelector,i=n.deprioritizedServers;r=t?t(e.description,o,i):o}catch(t){e.client.mongoLogger?.willLog(s.MongoLoggableComponent.SERVER_SELECTION,s.SeverityLevel.DEBUG)&&e.client.mongoLogger?.debug(s.MongoLoggableComponent.SERVER_SELECTION,new f.ServerSelectionFailedEvent(n.serverSelector,e.description,t,n.operationName)),n.reject(t);continue}if(0===r.length){n.waitingLogged||(e.client.mongoLogger?.willLog(s.MongoLoggableComponent.SERVER_SELECTION,s.SeverityLevel.INFORMATIONAL)&&e.client.mongoLogger?.info(s.MongoLoggableComponent.SERVER_SELECTION,new f.WaitingForSuitableServerEvent(n.serverSelector,e.description,0!==e.s.serverSelectionTimeoutMS?e.s.serverSelectionTimeoutMS-((0,d.processTimeMS)()-n.startTime):-1,n.operationName)),n.waitingLogged=!0),e.waitQueue.push(n);continue}if(1===r.length)a=e.s.servers.get(r[0].address);else{const t=(0,d.shuffle)(r,2),o=e.s.servers.get(t[0].address),n=e.s.servers.get(t[1].address);a=o&&n&&o.s.operationCount<n.s.operationCount?o:n}if(!a){const t=new i.MongoServerSelectionError("server selection returned a server description but the server was not found in the topology",e.description);return e.client.mongoLogger?.willLog(s.MongoLoggableComponent.SERVER_SELECTION,s.SeverityLevel.DEBUG)&&e.client.mongoLogger?.debug(s.MongoLoggableComponent.SERVER_SELECTION,new f.ServerSelectionFailedEvent(n.serverSelector,e.description,t,n.operationName)),void n.reject(t)}const c=n.transaction;t&&c&&c.isActive&&a&&c.pinServer(a),e.client.mongoLogger?.willLog(s.MongoLoggableComponent.SERVER_SELECTION,s.SeverityLevel.DEBUG)&&e.client.mongoLogger?.debug(s.MongoLoggableComponent.SERVER_SELECTION,new f.ServerSelectionSucceededEvent(n.serverSelector,n.topologyDescription,a.pool.address,n.operationName)),n.resolve(a)}if(e.waitQueue.length>0)for(const[,t]of e.s.servers)queueMicrotask((function(){return t.requestCheck()}))}t.Topology=O},36997:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoWriteConcernError=t.MongoServerSelectionError=t.MongoSystemError=t.MongoMissingDependencyError=t.MongoMissingCredentialsError=t.MongoCompatibilityError=t.MongoInvalidArgumentError=t.MongoParseError=t.MongoNetworkTimeoutError=t.MongoNetworkError=t.MongoClientClosedError=t.MongoTopologyClosedError=t.MongoCursorExhaustedError=t.MongoServerClosedError=t.MongoCursorInUseError=t.MongoOperationTimeoutError=t.MongoUnexpectedServerResponseError=t.MongoGridFSChunkError=t.MongoGridFSStreamError=t.MongoTailableCursorError=t.MongoChangeStreamError=t.MongoClientBulkWriteExecutionError=t.MongoClientBulkWriteCursorError=t.MongoClientBulkWriteError=t.MongoGCPError=t.MongoAzureError=t.MongoOIDCError=t.MongoAWSError=t.MongoKerberosError=t.MongoExpiredSessionError=t.MongoTransactionError=t.MongoNotConnectedError=t.MongoDecompressionError=t.MongoBatchReExecutionError=t.MongoStalePrimaryError=t.MongoRuntimeError=t.MongoAPIError=t.MongoDriverError=t.MongoServerError=t.MongoError=t.MongoErrorLabel=t.GET_MORE_RESUMABLE_CODES=t.MONGODB_ERROR_CODES=t.NODE_IS_RECOVERING_ERROR_MESSAGE=t.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE=t.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE=void 0,t.needsRetryableWriteLabel=function(e,n,r){if(e instanceof c)return!0;if(e instanceof o&&(n>=9||p(e))&&!e.hasErrorLabel(t.MongoErrorLabel.HandshakeError))return!1;if(e instanceof u){if("Mongos"===r&&n<9)return m.has(e.result.code??0);const t=e.result.writeConcernError.code??Number(e.code);return m.has(Number.isNaN(t)?0:t)}if(e instanceof o)return m.has(Number(e.code));return!!t.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(e.message)||!!t.NODE_IS_RECOVERING_ERROR_MESSAGE.test(e.message)},t.isRetryableWriteError=p,t.isRetryableReadError=function(e){if("number"==typeof e.code&&h.has(e.code))return!0;if(e instanceof c)return!0;return!!t.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(e.message)||!!t.NODE_IS_RECOVERING_ERROR_MESSAGE.test(e.message)},t.isNodeShuttingDownError=function(e){return!("number"!=typeof e.code||!S.has(e.code))},t.isStateChangeError=function(e){return E(e)||("number"==typeof(o=e).code?f.has(o.code):!E(o)&&t.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE.test(o.message));var o},t.isNetworkTimeoutError=function(e){return!!(e instanceof c&&e.message.match(/timed out/))},t.isResumableError=function(e,n){return null!=e&&e instanceof o&&(e instanceof c||(e instanceof d||(null!=n&&n>=9?e.code===t.MONGODB_ERROR_CODES.CursorNotFound||e.hasErrorLabel(t.MongoErrorLabel.ResumableChangeStreamError):"number"==typeof e.code&&t.GET_MORE_RESUMABLE_CODES.has(e.code))))},t.LEGACY_NOT_WRITABLE_PRIMARY_ERROR_MESSAGE=new RegExp("not master","i"),t.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE=new RegExp("not master or secondary","i"),t.NODE_IS_RECOVERING_ERROR_MESSAGE=new RegExp("node is recovering","i"),t.MONGODB_ERROR_CODES=Object.freeze({HostUnreachable:6,HostNotFound:7,AuthenticationFailed:18,NetworkTimeout:89,ShutdownInProgress:91,PrimarySteppedDown:189,ExceededTimeLimit:262,SocketException:9001,NotWritablePrimary:10107,InterruptedAtShutdown:11600,InterruptedDueToReplStateChange:11602,NotPrimaryNoSecondaryOk:13435,NotPrimaryOrSecondary:13436,StaleShardVersion:63,StaleEpoch:150,StaleConfig:13388,RetryChangeStream:234,FailedToSatisfyReadPreference:133,CursorNotFound:43,LegacyNotPrimary:10058,WriteConcernTimeout:64,NamespaceNotFound:26,IllegalOperation:20,MaxTimeMSExpired:50,UnknownReplWriteConcern:79,UnsatisfiableWriteConcern:100,Reauthenticate:391,ReadConcernMajorityNotAvailableYet:134}),t.GET_MORE_RESUMABLE_CODES=new Set([t.MONGODB_ERROR_CODES.HostUnreachable,t.MONGODB_ERROR_CODES.HostNotFound,t.MONGODB_ERROR_CODES.NetworkTimeout,t.MONGODB_ERROR_CODES.ShutdownInProgress,t.MONGODB_ERROR_CODES.PrimarySteppedDown,t.MONGODB_ERROR_CODES.ExceededTimeLimit,t.MONGODB_ERROR_CODES.SocketException,t.MONGODB_ERROR_CODES.NotWritablePrimary,t.MONGODB_ERROR_CODES.InterruptedAtShutdown,t.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,t.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk,t.MONGODB_ERROR_CODES.NotPrimaryOrSecondary,t.MONGODB_ERROR_CODES.StaleShardVersion,t.MONGODB_ERROR_CODES.StaleEpoch,t.MONGODB_ERROR_CODES.StaleConfig,t.MONGODB_ERROR_CODES.RetryChangeStream,t.MONGODB_ERROR_CODES.FailedToSatisfyReadPreference,t.MONGODB_ERROR_CODES.CursorNotFound]),t.MongoErrorLabel=Object.freeze({RetryableWriteError:"RetryableWriteError",TransientTransactionError:"TransientTransactionError",UnknownTransactionCommitResult:"UnknownTransactionCommitResult",ResumableChangeStreamError:"ResumableChangeStreamError",HandshakeError:"HandshakeError",ResetPool:"ResetPool",PoolRequestedRetry:"PoolRequestedRetry",InterruptInUseConnections:"InterruptInUseConnections",NoWritesPerformed:"NoWritesPerformed",RetryableError:"RetryableError",SystemOverloadedError:"SystemOverloadedError"});class o extends Error{get errorLabels(){return Array.from(this.errorLabelSet)}constructor(e,t){super(e,t),this.errorLabelSet=new Set}static buildErrorMessage(e){return"string"==typeof e?e:function(e){return null!=e&&"object"==typeof e&&"errors"in e&&Array.isArray(e.errors)}(e)&&0===e.message.length?0===e.errors.length?"AggregateError has an empty errors array. Please check the `cause` property for more information.":e.errors.map((({message:e})=>e)).join(", "):null!=e&&"object"==typeof e&&"message"in e&&"string"==typeof e.message?e.message:"empty error message"}get name(){return"MongoError"}get errmsg(){return this.message}hasErrorLabel(e){return this.errorLabelSet.has(e)}addErrorLabel(e){this.errorLabelSet.add(e)}}t.MongoError=o;class n extends o{constructor(e){if(super(e.message||e.errmsg||e.$err||"n/a"),e.errorLabels)for(const t of e.errorLabels)this.addErrorLabel(t);this.errorResponse=e;for(const t in e)"errorLabels"!==t&&"errmsg"!==t&&"message"!==t&&"errorResponse"!==t&&(this[t]=e[t])}get name(){return"MongoServerError"}}t.MongoServerError=n;class r extends o{constructor(e,t){super(e,t)}get name(){return"MongoDriverError"}}t.MongoDriverError=r;class i extends r{constructor(e,t){super(e,t)}get name(){return"MongoAPIError"}}t.MongoAPIError=i;class s extends r{constructor(e,t){super(e,t)}get name(){return"MongoRuntimeError"}}t.MongoRuntimeError=s,t.MongoStalePrimaryError=class extends s{constructor(e,t){super(e,t)}get name(){return"MongoStalePrimaryError"}},t.MongoBatchReExecutionError=class extends i{constructor(e="This batch has already been executed, create new batch to execute"){super(e)}get name(){return"MongoBatchReExecutionError"}},t.MongoDecompressionError=class extends s{constructor(e){super(e)}get name(){return"MongoDecompressionError"}},t.MongoNotConnectedError=class extends i{constructor(e){super(e)}get name(){return"MongoNotConnectedError"}},t.MongoTransactionError=class extends i{constructor(e){super(e)}get name(){return"MongoTransactionError"}},t.MongoExpiredSessionError=class extends i{constructor(e="Cannot use a session that has ended"){super(e)}get name(){return"MongoExpiredSessionError"}},t.MongoKerberosError=class extends s{constructor(e){super(e)}get name(){return"MongoKerberosError"}},t.MongoAWSError=class extends s{constructor(e,t){super(e,t)}get name(){return"MongoAWSError"}};class a extends s{constructor(e){super(e)}get name(){return"MongoOIDCError"}}t.MongoOIDCError=a,t.MongoAzureError=class extends a{constructor(e){super(e)}get name(){return"MongoAzureError"}},t.MongoGCPError=class extends a{constructor(e){super(e)}get name(){return"MongoGCPError"}},t.MongoClientBulkWriteError=class extends n{constructor(e){super(e),this.writeConcernErrors=[],this.writeErrors=new Map}get name(){return"MongoClientBulkWriteError"}},t.MongoClientBulkWriteCursorError=class extends s{constructor(e){super(e)}get name(){return"MongoClientBulkWriteCursorError"}},t.MongoClientBulkWriteExecutionError=class extends s{constructor(e){super(e)}get name(){return"MongoClientBulkWriteExecutionError"}},t.MongoChangeStreamError=class extends s{constructor(e){super(e)}get name(){return"MongoChangeStreamError"}},t.MongoTailableCursorError=class extends i{constructor(e="Tailable cursor does not support this operation"){super(e)}get name(){return"MongoTailableCursorError"}},t.MongoGridFSStreamError=class extends s{constructor(e){super(e)}get name(){return"MongoGridFSStreamError"}},t.MongoGridFSChunkError=class extends s{constructor(e){super(e)}get name(){return"MongoGridFSChunkError"}},t.MongoUnexpectedServerResponseError=class extends s{constructor(e,t){super(e,t)}get name(){return"MongoUnexpectedServerResponseError"}},t.MongoOperationTimeoutError=class extends r{get name(){return"MongoOperationTimeoutError"}},t.MongoCursorInUseError=class extends i{constructor(e="Cursor is already initialized"){super(e)}get name(){return"MongoCursorInUseError"}},t.MongoServerClosedError=class extends i{constructor(e="Server is closed"){super(e)}get name(){return"MongoServerClosedError"}},t.MongoCursorExhaustedError=class extends i{constructor(e){super(e||"Cursor is exhausted")}get name(){return"MongoCursorExhaustedError"}},t.MongoTopologyClosedError=class extends i{constructor(e="Topology is closed"){super(e)}get name(){return"MongoTopologyClosedError"}},t.MongoClientClosedError=class extends i{constructor(){super("Operation interrupted because client was closed")}get name(){return"MongoClientClosedError"}};class c extends o{constructor(e,t){super(e,{cause:t?.cause}),this.beforeHandshake=!!t?.beforeHandshake}get name(){return"MongoNetworkError"}}t.MongoNetworkError=c,t.MongoNetworkTimeoutError=class extends c{constructor(e,t){super(e,t)}get name(){return"MongoNetworkTimeoutError"}},t.MongoParseError=class extends r{constructor(e){super(e)}get name(){return"MongoParseError"}},t.MongoInvalidArgumentError=class extends i{constructor(e,t){super(e,t)}get name(){return"MongoInvalidArgumentError"}},t.MongoCompatibilityError=class extends i{constructor(e){super(e)}get name(){return"MongoCompatibilityError"}},t.MongoMissingCredentialsError=class extends i{constructor(e){super(e)}get name(){return"MongoMissingCredentialsError"}},t.MongoMissingDependencyError=class extends i{constructor(e,t){super(e,t),this.dependencyName=t.dependencyName}get name(){return"MongoMissingDependencyError"}};class l extends o{constructor(e,t){t&&t.error?super(o.buildErrorMessage(t.error.message||t.error),{cause:t.error}):super(e),t&&(this.reason=t),this.code=t.error?.code}get name(){return"MongoSystemError"}}t.MongoSystemError=l;class d extends l{constructor(e,t){super(e,t)}get name(){return"MongoServerSelectionError"}}t.MongoServerSelectionError=d;class u extends n{constructor(e){super({...e.writeConcernError,...e}),this.errInfo=e.writeConcernError.errInfo,this.result=e}get name(){return"MongoWriteConcernError"}}t.MongoWriteConcernError=u;const h=new Set([t.MONGODB_ERROR_CODES.HostUnreachable,t.MONGODB_ERROR_CODES.HostNotFound,t.MONGODB_ERROR_CODES.NetworkTimeout,t.MONGODB_ERROR_CODES.ShutdownInProgress,t.MONGODB_ERROR_CODES.PrimarySteppedDown,t.MONGODB_ERROR_CODES.SocketException,t.MONGODB_ERROR_CODES.NotWritablePrimary,t.MONGODB_ERROR_CODES.InterruptedAtShutdown,t.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,t.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk,t.MONGODB_ERROR_CODES.NotPrimaryOrSecondary,t.MONGODB_ERROR_CODES.ExceededTimeLimit,t.MONGODB_ERROR_CODES.ReadConcernMajorityNotAvailableYet]),m=h;function p(e){return e.hasErrorLabel(t.MongoErrorLabel.RetryableWriteError)||e.hasErrorLabel(t.MongoErrorLabel.PoolRequestedRetry)}const g=new Set([t.MONGODB_ERROR_CODES.ShutdownInProgress,t.MONGODB_ERROR_CODES.PrimarySteppedDown,t.MONGODB_ERROR_CODES.InterruptedAtShutdown,t.MONGODB_ERROR_CODES.InterruptedDueToReplStateChange,t.MONGODB_ERROR_CODES.NotPrimaryOrSecondary]),f=new Set([t.MONGODB_ERROR_CODES.NotWritablePrimary,t.MONGODB_ERROR_CODES.NotPrimaryNoSecondaryOk,t.MONGODB_ERROR_CODES.LegacyNotPrimary]),S=new Set([t.MONGODB_ERROR_CODES.InterruptedAtShutdown,t.MONGODB_ERROR_CODES.ShutdownInProgress]);function E(e){return"number"==typeof e.code?g.has(e.code):t.LEGACY_NOT_PRIMARY_OR_SECONDARY_ERROR_MESSAGE.test(e.message)||t.NODE_IS_RECOVERING_ERROR_MESSAGE.test(e.message)}},39131:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.executeOperation=async function(e,t,o){if(!(t instanceof d.AbstractOperation))throw new r.MongoRuntimeError("This method requires a valid operation instance");const p=null==e.topology?await(0,c.abortable)(m(e),t.options):e.topology;let g,f=t.session;if(null==f)g=Symbol(),f=e.startSession({owner:g,explicit:!1});else{if(f.hasEnded)throw new r.MongoExpiredSessionError("Use of expired sessions is not permitted");if(f.snapshotEnabled&&(0,c.maxWireVersion)(p)<n.MIN_SUPPORTED_SNAPSHOT_READS_WIRE_VERSION)throw new r.MongoCompatibilityError("Snapshot reads require MongoDB 5.0 or later");if(f.client!==e)throw new r.MongoInvalidArgumentError("ClientSession must be from the same MongoClient")}t.session??=f;const S=t.readPreference??i.ReadPreference.primary,E=!!f?.inTransaction(),y=t.hasAspect(d.Aspect.READ_OPERATION);if(E&&!S.equals(i.ReadPreference.primary)&&(y||"runCommand"===t.commandName))throw new r.MongoTransactionError(`Read preference in a transaction must be primary, not: ${S.mode}`);f?.isPinned&&f.transaction.isCommitted&&!t.bypassPinningCheck&&f.unpin(),o??=a.TimeoutContext.create({session:f,serverSelectionTimeoutMS:e.s.options.serverSelectionTimeoutMS,waitQueueTimeoutMS:e.s.options.waitQueueTimeoutMS,timeoutMS:t.options.timeoutMS});try{return await async function(e,{topology:t,timeoutContext:o,session:n,readPreference:i}){let a;a=e.hasAspect(d.Aspect.MUST_SELECT_SAME_SERVER)?(0,s.sameServerSelector)(e.server?.description):e instanceof l.AggregateOperation&&e.hasWriteStage?(0,s.secondaryWritableServerSelector)(t.commonWireVersion,i):i;let m=await t.selectServer(a,{session:n,operationName:e.commandName,timeoutContext:o,signal:e.options.signal,deprioritizedServers:new s.DeprioritizedServers});const p=e.hasAspect(d.Aspect.READ_OPERATION),g=e.hasAspect(d.Aspect.WRITE_OPERATION),f=n?.inTransaction()??!1,S=t.s.options.retryReads&&!f&&e.canRetryRead,E=t.s.options.retryWrites&&!f&&(0,c.supportsRetryableWrites)(m)&&e.canRetryWrite,y=e.hasAspect(d.Aspect.RETRYABLE)&&null!=n&&(p&&S||g&&E);g&&E&&null!=n&&(e.options.willRetryWrite=!0,n.incrementTransactionNumber());const b=y?o.csotEnabled()?1/0:2:1;let O;const C=new s.DeprioritizedServers;for(let i=0;i<b;i++){if(O){if(g&&O.code===u)throw new r.MongoServerError({message:h,errmsg:h,originalError:O});if(e.hasAspect(d.Aspect.COMMAND_BATCHING)&&!e.canRetryWrite)throw O;if(g&&!(0,r.isRetryableWriteError)(O))throw O;if(p&&!(0,r.isRetryableReadError)(O))throw O;if(O instanceof r.MongoNetworkError&&e.hasAspect(d.Aspect.CURSOR_CREATING)&&null!=n&&n.isPinned&&!n.inTransaction()&&n.unpin({force:!0,forceClear:!0}),m=await t.selectServer(a,{session:n,operationName:e.commandName,deprioritizedServers:C,signal:e.options.signal}),g&&!(0,c.supportsRetryableWrites)(m))throw new r.MongoUnexpectedServerResponseError("Selected server does not support retryable writes")}e.server=m;try{i>0&&e.hasAspect(d.Aspect.COMMAND_BATCHING)&&e.resetBatch();try{const t=await m.command(e,o);return e.handleOk(t)}catch(t){return e.handleError(t)}}catch(e){if(!(e instanceof r.MongoError))throw e;if(null!=O&&e.hasErrorLabel(r.MongoErrorLabel.NoWritesPerformed))throw O;C.add(m.description),O=e,o.clear()}}throw O??new r.MongoRuntimeError("Tried to propagate retryability error, but no error was found.")}(t,{topology:p,timeoutContext:o,session:f,readPreference:S})}finally{null!=f?.owner&&f.owner===g&&await f.endSession()}},t.autoConnect=m;const n=o(60889),r=o(36997),i=o(74891),s=o(26119),a=o(33628),c=o(30306),l=o(86065),d=o(28947),u=r.MONGODB_ERROR_CODES.IllegalOperation,h="This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.";async function m(e){if(null==e.topology){if(e.s.hasBeenClosed)throw new r.MongoNotConnectedError("Client must be connected before running operations");e.s.options.__skipPingOnConnect=!0;try{if(await e.connect(),null==e.topology)throw new r.MongoRuntimeError("client.connect did not create a topology but also did not throw");return e.topology}finally{delete e.s.options.__skipPingOnConnect}}return e.topology}},39272:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SrvPoller=t.SrvPollingEvent=void 0;const n=o(79498),r=o(31713),i=o(36997),s=o(72361),a=o(30306);class c{constructor(e){this.srvRecords=e}hostnames(){return new Set(this.srvRecords.map((e=>a.HostAddress.fromSrvRecord(e).toString())))}}t.SrvPollingEvent=c;class l extends s.TypedEventEmitter{static{this.SRV_RECORD_DISCOVERY="srvRecordDiscovery"}constructor(e){if(super(),this.on("error",a.noop),!e||!e.srvHost)throw new i.MongoRuntimeError("Options for SrvPoller must exist and include srvHost");this.srvHost=e.srvHost,this.srvMaxHosts=e.srvMaxHosts??0,this.srvServiceName=e.srvServiceName??"mongodb",this.rescanSrvIntervalMS=6e4,this.heartbeatFrequencyMS=e.heartbeatFrequencyMS??1e4,this.haMode=!1,this.generation=0,this._timeout=void 0}get srvAddress(){return`_${this.srvServiceName}._tcp.${this.srvHost}`}get intervalMS(){return this.haMode?this.heartbeatFrequencyMS:this.rescanSrvIntervalMS}start(){this._timeout||this.schedule()}stop(){this._timeout&&((0,r.clearTimeout)(this._timeout),this.generation+=1,this._timeout=void 0)}schedule(){this._timeout&&(0,r.clearTimeout)(this._timeout),this._timeout=(0,r.setTimeout)((()=>{this._poll().then(void 0,a.squashError)}),this.intervalMS)}success(e){this.haMode=!1,this.schedule(),this.emit(l.SRV_RECORD_DISCOVERY,new c(e))}failure(){this.haMode=!0,this.schedule()}async _poll(){const e=this.generation;let t;try{t=await n.promises.resolveSrv(this.srvAddress)}catch{return void this.failure()}if(e!==this.generation)return;const o=[];for(const e of t)try{(0,a.checkParentDomainMatch)(e.name,this.srvHost),o.push(e)}catch(e){(0,a.squashError)(e)}o.length?this.success(o):this.failure()}}t.SrvPoller=l},40083:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.functionCtorWithoutProps=function(e){function t(...t){return new.target?Reflect.construct(e,t,new.target):new e(...t)}Object.setPrototypeOf(t,Object.getPrototypeOf(e));const o=Object.getOwnPropertyDescriptor(e,"name");return o&&Object.defineProperty(t,"name",o),t},t.assignAll=function(e,...t){const o=[];for(const e of t)o.push(...Object.entries(Object.getOwnPropertyDescriptors(e)));const n=Object.fromEntries(o);for(const t of Object.getOwnPropertyNames(n))!1===Object.getOwnPropertyDescriptor(e,t)?.configurable&&(e[t]=n[t].value,delete n[t]);return Object.defineProperties(e,n),e},t.pickWithExactKeyMatch=function(e,t){return Object.create(Object.getPrototypeOf(e),Object.fromEntries(Object.entries(Object.getOwnPropertyDescriptors(e)).filter((([e])=>t.includes(e)))))},t.assertArgsDefinedType=function(e,t,o){e.forEach(((e,s)=>{const a=t[s];if(void 0===e){if(!0!==a&&Array.isArray(a)&&a.includes(void 0))return;throw new n.MongoshInvalidInputError(`Missing required argument at position ${s}${i(o)}`,n.CommonErrors.InvalidArgument)}if(!0===a)return;const c="string"==typeof a?[a]:a,l=c.includes(typeof e),d=c.includes(`bson:${(0,r.getBsonType)(e)}`);if(!l&&!d){const t=c.filter((e=>void 0!==e)).map((e=>e?.replace(/^bson:/,""))).join(" or ");throw new n.MongoshInvalidInputError(`Argument at position ${s} must be of type ${t}, got ${typeof e} instead${i(o)}`,n.CommonErrors.InvalidArgument)}}))};const n=o(92762),r=o(34037);function i(e){return e?` (${e})`:""}},40818:function(e,t,o){var n=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),r=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||n(t,e,o)},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceProviderCore=t.DEFAULT_DB=t.getConnectExtraInfo=void 0,o(36667);const s=o(57319);Object.defineProperty(t,"ServiceProviderCore",{enumerable:!0,get:function(){return s.ServiceProviderCore}});const a=i(o(97));t.getConnectExtraInfo=a.default,t.DEFAULT_DB="test",r(o(93361),t),r(o(28749),t)},40927:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CursorTimeoutContext=t.AbstractCursor=t.CursorTimeoutMode=t.CURSOR_FLAGS=void 0;const n=o(64371),r=o(77953),i=o(36997),s=o(72361),a=o(39131),c=o(87192),l=o(88e3),d=o(86552),u=o(74891),h=o(86098),m=o(33628),p=o(30306);function g(){this.client.s.activeCursors.delete(this)}t.CURSOR_FLAGS=["tailable","oplogReplay","noCursorTimeout","awaitData","exhaust","partial"],t.CursorTimeoutMode=Object.freeze({ITERATION:"iteration",LIFETIME:"cursorLifetime"});class f extends s.TypedEventEmitter{static{this.CLOSE="close"}constructor(e,o,n={}){if(super(),this.documents=null,this.hasEmittedClose=!1,this.on("error",p.noop),!e.s.isMongoClient)throw new i.MongoRuntimeError("Cursor must be constructed with MongoClient");if(this.cursorClient=e,this.cursorNamespace=o,this.cursorId=null,this.initialized=!1,this.isClosed=!1,this.isKilled=!1,this.cursorOptions={readPreference:n.readPreference&&n.readPreference instanceof u.ReadPreference?n.readPreference:u.ReadPreference.primary,...(0,r.pluckBSONSerializeOptions)(n),timeoutMS:n?.timeoutContext?.csotEnabled()?n.timeoutContext.timeoutMS:n.timeoutMS,tailable:n.tailable,awaitData:n.awaitData},null!=this.cursorOptions.timeoutMS)if(null==n.timeoutMode)if(n.tailable){if(n.awaitData&&null!=n.maxAwaitTimeMS&&n.maxAwaitTimeMS>=this.cursorOptions.timeoutMS)throw new i.MongoInvalidArgumentError("Cannot specify maxAwaitTimeMS >= timeoutMS for a tailable awaitData cursor");this.cursorOptions.timeoutMode=t.CursorTimeoutMode.ITERATION}else this.cursorOptions.timeoutMode=t.CursorTimeoutMode.LIFETIME;else{if(n.tailable&&n.timeoutMode===t.CursorTimeoutMode.LIFETIME)throw new i.MongoInvalidArgumentError("Cannot set tailable cursor's timeoutMode to LIFETIME");this.cursorOptions.timeoutMode=n.timeoutMode}else if(null!=n.timeoutMode)throw new i.MongoInvalidArgumentError("Cannot set timeoutMode without setting timeoutMS");this.cursorOptions.omitMaxTimeMS=null!=this.cursorOptions.timeoutMS&&(this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&!this.cursorOptions.tailable||this.cursorOptions.tailable&&!this.cursorOptions.awaitData);const s=d.ReadConcern.fromOptions(n);s&&(this.cursorOptions.readConcern=s),"number"==typeof n.batchSize&&(this.cursorOptions.batchSize=n.batchSize),void 0!==n.comment&&(this.cursorOptions.comment=n.comment),"number"==typeof n.maxTimeMS&&(this.cursorOptions.maxTimeMS=n.maxTimeMS),"number"==typeof n.maxAwaitTimeMS&&(this.cursorOptions.maxAwaitTimeMS=n.maxAwaitTimeMS),this.cursorSession=n.session??null,this.deserializationOptions={...this.cursorOptions,validation:{utf8:!1!==n?.enableUtf8Validation}},this.timeoutContext=n.timeoutContext,this.signal=n.signal,this.abortListener=(0,p.addAbortListener)(this.signal,(()=>{this.close().then(void 0,p.squashError)})),this.trackCursor()}get id(){return this.cursorId??void 0}get isDead(){return(this.cursorId?.isZero()??!1)||this.isClosed||this.isKilled}get client(){return this.cursorClient}get server(){return this.selectedServer}get namespace(){return this.cursorNamespace}get readPreference(){return this.cursorOptions.readPreference}get readConcern(){return this.cursorOptions.readConcern}get session(){return this.cursorSession}set session(e){this.cursorSession=e}get closed(){return this.isClosed&&0===(this.documents?.length??0)}get killed(){return this.isKilled}get loadBalanced(){return!!this.cursorClient.topology?.loadBalanced}async[Symbol.asyncDispose](){await this.close()}trackCursor(){this.cursorClient.s.activeCursors.add(this),this.listeners("close").includes(g)||this.once("close",g)}bufferedCount(){return this.documents?.length??0}readBufferedDocuments(e){const t=[],o=Math.min(e??this.documents?.length??0,this.documents?.length??0);for(let e=0;e<o;e++){const e=this.documents?.shift(this.deserializationOptions);null!=e&&t.push(e)}return t}async*[Symbol.asyncIterator](){if(this.signal?.throwIfAborted(),!this.closed)try{for(;;){if(this.isKilled)return;if(this.closed)return;if(null!=this.cursorId&&this.isDead&&0===(this.documents?.length??0))return;const e=await this.next();if(null===e)return;yield e,this.signal?.throwIfAborted()}}finally{if(!this.isClosed)try{await this.close()}catch(e){(0,p.squashError)(e)}}}stream(){const e=new S(this),t=(0,p.addAbortListener)(this.signal,(function(){e.destroy(this.reason)}));return e.once("end",(()=>{t?.[p.kDispose]()})),e}async hasNext(){if(this.signal?.throwIfAborted(),this.cursorId===r.Long.ZERO)return!1;this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&null!=this.cursorId&&this.timeoutContext?.refresh();try{do{if(0!==(this.documents?.length??0))return!0;await this.fetchBatch()}while(!this.isDead||0!==(this.documents?.length??0))}finally{this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&this.timeoutContext?.clear()}return!1}async next(){if(this.signal?.throwIfAborted(),this.cursorId===r.Long.ZERO)throw new i.MongoCursorExhaustedError;this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&null!=this.cursorId&&this.timeoutContext?.refresh();try{do{const e=this.documents?.shift(this.deserializationOptions);if(null!=e)return null!=this.transform?await this.transformDocument(e):e;await this.fetchBatch()}while(!this.isDead||0!==(this.documents?.length??0))}finally{this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&this.timeoutContext?.clear()}return null}async tryNext(){if(this.signal?.throwIfAborted(),this.cursorId===r.Long.ZERO)throw new i.MongoCursorExhaustedError;this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&null!=this.cursorId&&this.timeoutContext?.refresh();try{let e=this.documents?.shift(this.deserializationOptions);if(null!=e)return null!=this.transform?await this.transformDocument(e):e;if(await this.fetchBatch(),e=this.documents?.shift(this.deserializationOptions),null!=e)return null!=this.transform?await this.transformDocument(e):e}finally{this.cursorOptions.timeoutMode===t.CursorTimeoutMode.ITERATION&&this.timeoutContext?.clear()}return null}async forEach(e){if(this.signal?.throwIfAborted(),"function"!=typeof e)throw new i.MongoInvalidArgumentError('Argument "iterator" must be a function');for await(const t of this)if(!1===e(t))break}async close(e){await this.cleanup(e?.timeoutMS)}async toArray(){this.signal?.throwIfAborted();const e=[];for await(const t of this){e.push(t);const o=this.readBufferedDocuments();if(null!=this.transform)for(const t of o)e.push(await this.transformDocument(t));else for(const t of o)e.push(t)}return e}addCursorFlag(e,o){if(this.throwIfInitialized(),!t.CURSOR_FLAGS.includes(e))throw new i.MongoInvalidArgumentError(`Flag ${e} is not one of ${t.CURSOR_FLAGS}`);if("boolean"!=typeof o)throw new i.MongoInvalidArgumentError(`Flag ${e} must be a boolean value`);return this.cursorOptions[e]=o,this}map(e){this.throwIfInitialized();const t=this.transform;return this.transform=t?o=>e(t(o)):e,this}withReadPreference(e){if(this.throwIfInitialized(),e instanceof u.ReadPreference)this.cursorOptions.readPreference=e;else{if("string"!=typeof e)throw new i.MongoInvalidArgumentError(`Invalid read preference: ${e}`);this.cursorOptions.readPreference=u.ReadPreference.fromString(e)}return this}withReadConcern(e){this.throwIfInitialized();const t=d.ReadConcern.fromOptions({readConcern:e});return t&&(this.cursorOptions.readConcern=t),this}maxTimeMS(e){if(this.throwIfInitialized(),"number"!=typeof e)throw new i.MongoInvalidArgumentError("Argument for maxTimeMS must be a number");return this.cursorOptions.maxTimeMS=e,this}batchSize(e){if(this.throwIfInitialized(),this.cursorOptions.tailable)throw new i.MongoTailableCursorError("Tailable cursor does not support batchSize");if("number"!=typeof e)throw new i.MongoInvalidArgumentError('Operation "batchSize" requires an integer');return this.cursorOptions.batchSize=e,this}rewind(){if(this.timeoutContext&&this.timeoutContext.owner!==this)throw new i.MongoAPIError("Cannot rewind cursor that does not own its timeout context.");this.initialized&&(this.cursorId=null,this.documents?.clear(),this.timeoutContext?.clear(),this.timeoutContext=void 0,this.isClosed=!1,this.isKilled=!1,this.initialized=!1,this.hasEmittedClose=!1,this.trackCursor(),!1===this.cursorSession?.explicit&&(this.cursorSession.hasEnded||this.cursorSession.endSession().then(void 0,p.squashError),this.cursorSession=null))}async getMore(){if(null==this.cursorId)throw new i.MongoRuntimeError("Unexpected null cursor id. A cursor creating command should have set this");if(null==this.selectedServer)throw new i.MongoRuntimeError("Unexpected null selectedServer. A cursor creating command should have set this");if(null==this.cursorSession)throw new i.MongoRuntimeError("Unexpected null session. A cursor creating command should have set this");const e={...this.cursorOptions,session:this.cursorSession,batchSize:this.cursorOptions.batchSize},t=new c.GetMoreOperation(this.cursorNamespace,this.cursorId,this.selectedServer,e);return await(0,a.executeOperation)(this.cursorClient,t,this.timeoutContext)}async cursorInit(){null!=this.cursorOptions.timeoutMS&&(this.timeoutContext??=new E(m.TimeoutContext.create({serverSelectionTimeoutMS:this.client.s.options.serverSelectionTimeoutMS,timeoutMS:this.cursorOptions.timeoutMS}),this));try{this.cursorSession??=this.cursorClient.startSession({owner:this,explicit:!1});const e=await this._initialize(this.cursorSession);this.cursorOptions.omitMaxTimeMS=null!=this.cursorOptions.timeoutMS;const t=e.response;this.selectedServer=e.server,this.cursorId=t.id,this.cursorNamespace=t.ns??this.namespace,this.documents=t,this.initialized=!0}catch(e){throw this.initialized=!0,await this.cleanup(void 0,e),e}this.isDead&&await this.cleanup()}async fetchBatch(){if(!this.isClosed)if(this.isDead)await this.cleanup();else if(null!=this.cursorId||(await this.cursorInit(),0===(this.documents?.length??0)&&!this.isDead)){try{const e=await this.getMore();this.cursorId=e.id,this.documents=e}catch(e){try{await this.cleanup(void 0,e)}catch(e){(0,p.squashError)(e)}throw e}this.isDead&&await this.cleanup()}}async cleanup(e,t){this.abortListener?.[p.kDispose](),this.isClosed=!0;const o=()=>null!=e?(this.timeoutContext?.clear(),new E(m.TimeoutContext.create({serverSelectionTimeoutMS:this.client.s.options.serverSelectionTimeoutMS,timeoutMS:e}),this)):this.timeoutContext?.refreshed();await(async e=>{try{await e()}finally{this.emitClose()}})((async()=>{const e=this.cursorSession;if(e)try{if(!this.isKilled&&this.cursorId&&!this.cursorId.isZero()&&this.cursorNamespace&&this.selectedServer&&!e.hasEnded){this.isKilled=!0;const t=this.cursorId;this.cursorId=r.Long.ZERO,await(0,a.executeOperation)(this.cursorClient,new l.KillCursorsOperation(t,this.cursorNamespace,this.selectedServer,{session:e}),o())}}catch(e){(0,p.squashError)(e)}finally{e.owner===this&&await e.endSession({error:t}),e.inTransaction()||(0,h.maybeClearPinnedConnection)(e,{error:t})}}))}emitClose(){try{this.hasEmittedClose||0!==(this.documents?.length??0)&&!this.isClosed||this.emit("close")}finally{this.hasEmittedClose=!0}}async transformDocument(e){if(null==this.transform)return e;try{const t=this.transform(e);if(null===t){const e="Cursor returned a `null` document, but the cursor is not exhausted. Mapping documents to `null` is not supported in the cursor transform.";throw new i.MongoAPIError(e)}return t}catch(e){try{await this.close()}catch(e){(0,p.squashError)(e)}throw e}}throwIfInitialized(){if(this.initialized)throw new i.MongoCursorInUseError}}t.AbstractCursor=f;class S extends n.Readable{constructor(e){super({objectMode:!0,autoDestroy:!1,highWaterMark:1}),this._readInProgress=!1,this._cursor=e}_read(e){this._readInProgress||(this._readInProgress=!0,this._readNext())}_destroy(e,t){this._cursor.close().then((()=>t(e)),(e=>t(e)))}_readNext(){this._cursor.id!==r.Long.ZERO?this._cursor.next().then((e=>{if(null==e)this.push(null);else if(this.destroyed)this._cursor.close().then(void 0,p.squashError);else{if(this.push(e))return this._readNext();this._readInProgress=!1}}),(e=>e.message.match(/server is closed/)?(this._cursor.close().then(void 0,p.squashError),this.push(null)):e.message.match(/operation was interrupted/)?this.push(null):this.destroy(e))).catch((e=>{this._readInProgress=!1,this.destroy(e)})):this.push(null)}}class E extends m.TimeoutContext{constructor(e,t){super(),this.timeoutContext=e,this.owner=t}get serverSelectionTimeout(){return this.timeoutContext.serverSelectionTimeout}get connectionCheckoutTimeout(){return this.timeoutContext.connectionCheckoutTimeout}get clearServerSelectionTimeout(){return this.timeoutContext.clearServerSelectionTimeout}get timeoutForSocketWrite(){return this.timeoutContext.timeoutForSocketWrite}get timeoutForSocketRead(){return this.timeoutContext.timeoutForSocketRead}csotEnabled(){return this.timeoutContext.csotEnabled()}refresh(){if("symbol"!=typeof this.owner)return this.timeoutContext.refresh()}clear(){if("symbol"!=typeof this.owner)return this.timeoutContext.clear()}get maxTimeMS(){return this.timeoutContext.maxTimeMS}get timeoutMS(){return this.timeoutContext.csotEnabled()?this.timeoutContext.timeoutMS:null}refreshed(){return new E(this.timeoutContext.refreshed(),this.owner)}addMaxTimeMSToCommand(e,t){this.timeoutContext.addMaxTimeMSToCommand(e,t)}getSocketTimeoutMS(){return this.timeoutContext.getSocketTimeoutMS()}}t.CursorTimeoutContext=E},41330:function(e,t,o){var n=this&&this.__createBinding||(Object.create?function(e,t,o,n){void 0===n&&(n=o);var r=Object.getOwnPropertyDescriptor(t,o);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,r)}:function(e,t,o,n){void 0===n&&(n=o),e[n]=t[o]}),r=this&&this.__exportStar||function(e,t){for(var o in e)"default"===o||Object.prototype.hasOwnProperty.call(t,o)||n(t,e,o)};Object.defineProperty(t,"__esModule",{value:!0}),t.makeBsonStringifiers=t.makePrintableBson=t.constructShellBson=void 0,r(o(34037),t);var i=o(64543);Object.defineProperty(t,"constructShellBson",{enumerable:!0,get:function(){return i.constructShellBson}});var s=o(60892);Object.defineProperty(t,"makePrintableBson",{enumerable:!0,get:function(){return s.makePrintableBson}}),Object.defineProperty(t,"makeBsonStringifiers",{enumerable:!0,get:function(){return s.makeBsonStringifiers}})},41374:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.loadGCPCredentials=async function(e){const t=(0,n.getGcpMetadata)();if("kModuleError"in t)return e;const{access_token:o}=await t.instance({property:"service-accounts/default/token"});return{...e,gcp:{accessToken:o}}};const n=o(98517)},41539:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CommandOperation=void 0;const n=o(60889),r=o(36997),i=o(27272),s=o(86552),a=o(30306),c=o(71259),l=o(28947);class d extends l.AbstractOperation{constructor(e,t){super(t),this.options=t??{};const o=t?.dbName||t?.authdb;if(this.ns=o?new a.MongoDBNamespace(o,"$cmd"):e?e.s.namespace.withCollection("$cmd"):new a.MongoDBNamespace("admin","$cmd"),this.readConcern=s.ReadConcern.fromOptions(t),this.writeConcern=c.WriteConcern.fromOptions(t),this.hasAspect(l.Aspect.EXPLAINABLE))this.explain=i.Explain.fromOptions(t),this.explain&&(0,i.validateExplainTimeoutOptions)(this.options,this.explain);else if(null!=t?.explain)throw new r.MongoInvalidArgumentError('Option "explain" is not supported on this command')}get canRetryWrite(){return this.hasAspect(l.Aspect.EXPLAINABLE)?null==this.explain:super.canRetryWrite}buildOptions(e){return{...this.options,...this.bsonOptions,timeoutContext:e,readPreference:this.readPreference,session:this.session}}buildCommand(e,t){const o=this.buildCommandDocument(e,t),r=this.session&&this.session.inTransaction();return this.readConcern&&(0,a.commandSupportsReadConcern)(o)&&!r&&Object.assign(o,{readConcern:this.readConcern}),this.writeConcern&&this.hasAspect(l.Aspect.WRITE_OPERATION)&&!r&&c.WriteConcern.apply(o,this.writeConcern),this.options.collation&&"object"==typeof this.options.collation&&!this.hasAspect(l.Aspect.SKIP_COLLATION)&&Object.assign(o,{collation:this.options.collation}),"number"==typeof this.options.maxTimeMS&&(o.maxTimeMS=this.options.maxTimeMS),null!=this.options.rawData&&this.hasAspect(l.Aspect.SUPPORTS_RAW_DATA)&&(0,a.maxWireVersion)(e)>=n.MIN_SUPPORTED_RAW_DATA_WIRE_VERSION&&(o.rawData=this.options.rawData),this.hasAspect(l.Aspect.EXPLAINABLE)&&this.explain?(0,i.decorateWithExplain)(o,this.explain):o}}t.CommandOperation=d},41720:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoDBOIDC=t.OIDC_WORKFLOWS=t.OIDC_VERSION=void 0;const n=o(36997),r=o(68950),i=o(87187),s=o(11280),a=o(22643),c=o(66601),l=o(60239),d=o(26482);t.OIDC_VERSION=1,t.OIDC_WORKFLOWS=new Map,t.OIDC_WORKFLOWS.set("test",(()=>new i.AutomatedCallbackWorkflow(new l.TokenCache,d.callback))),t.OIDC_WORKFLOWS.set("azure",(()=>new i.AutomatedCallbackWorkflow(new l.TokenCache,s.callback))),t.OIDC_WORKFLOWS.set("gcp",(()=>new i.AutomatedCallbackWorkflow(new l.TokenCache,a.callback))),t.OIDC_WORKFLOWS.set("k8s",(()=>new i.AutomatedCallbackWorkflow(new l.TokenCache,c.callback)));class u extends r.AuthProvider{constructor(e){if(super(),!e)throw new n.MongoInvalidArgumentError("No workflow provided to the OIDC auth provider.");this.workflow=e}async auth(e){const{connection:t,reauthenticating:o,response:n}=e;if(n?.speculativeAuthenticate?.done&&!o)return;const r=h(e);o?await this.workflow.reauthenticate(t,r):await this.workflow.execute(t,r,n)}async prepare(e,t){const{connection:o}=t,n=h(t);return{...e,...await this.workflow.speculativeAuth(o,n)}}}function h(e){const{credentials:t}=e;if(!t)throw new n.MongoMissingCredentialsError("AuthContext must provide credentials.");return t}t.MongoDBOIDC=u},43975:(e,t,o)=>{var n=o(21655).URL;Object.defineProperty(t,"__esModule",{value:!0}),t.tokenCache=t.AzureCredentialCache=t.AZURE_BASE_URL=void 0,t.addAzureParams=c,t.prepareRequest=l,t.fetchAzureKMSToken=d,t.loadAzureCredentials=async function(e){return{...e,azure:await t.tokenCache.getToken()}};const r=o(36997),i=o(30306),s=o(64578);t.AZURE_BASE_URL="http://169.254.169.254/metadata/identity/oauth2/token?";class a{constructor(){this.cachedToken=null}async getToken(){return(null==this.cachedToken||this.needsRefresh(this.cachedToken))&&(this.cachedToken=await this._getToken()),{accessToken:this.cachedToken.accessToken}}needsRefresh(e){return e.expiresOnTimestamp-Date.now()<=6e3}resetCache(){this.cachedToken=null}_getToken(){return d()}}function c(e,t,o){return e.searchParams.append("api-version","2018-02-01"),e.searchParams.append("resource",t),o&&e.searchParams.append("client_id",o),e}function l(e){const o=new n(e.url?.toString()??t.AZURE_BASE_URL);return c(o,"https://vault.azure.net"),{headers:{...e.headers,"Content-Type":"application/json",Metadata:!0},url:o}}async function d(e={}){const{headers:t,url:o}=l(e);try{const e=await(0,i.get)(o,{headers:t});return await async function(e){const{status:t,body:o}=e,n=(()=>{try{return JSON.parse(o)}catch{throw new s.MongoCryptAzureKMSRequestError("Malformed JSON body in GET request.")}})();if(200!==t)throw new s.MongoCryptAzureKMSRequestError("Unable to complete request.",n);if(!n.access_token)throw new s.MongoCryptAzureKMSRequestError("Malformed response body - missing field `access_token`.");if(!n.expires_in)throw new s.MongoCryptAzureKMSRequestError("Malformed response body - missing field `expires_in`.");const r=1e3*Number(n.expires_in);if(Number.isNaN(r))throw new s.MongoCryptAzureKMSRequestError("Malformed response body - unable to parse int from `expires_in` field.");return{accessToken:n.access_token,expiresOnTimestamp:Date.now()+r}}(e)}catch(e){if(e instanceof r.MongoNetworkTimeoutError)throw new s.MongoCryptAzureKMSRequestError(`[Azure KMS] ${e.message}`);throw e}}t.AzureCredentialCache=a,t.tokenCache=new a},44058:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExplainableCursor=void 0;const n=o(40927);class r extends n.AbstractCursor{resolveExplainTimeoutOptions(e,t){let o,n;return null==e&&null==t?(o=void 0,n=void 0):null!=e&&null==t?(o="object"!=typeof e||"verbosity"in e?e:void 0,n="object"==typeof e&&"timeoutMS"in e?e:void 0):(o=e,n=t),{timeout:n,explain:o}}}t.ExplainableCursor=r},44714:(e,t,o)=>{var n=o(34110).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.GridFSBucketWriteStream=void 0;const r=o(64371),i=o(77953),s=o(40927),a=o(36997),c=o(33628),l=o(30306),d=o(71259);class u extends r.Writable{constructor(e,t,o){super(),this.gridFSFile=null,o=o??{},this.bucket=e,this.chunks=e.s._chunksCollection,this.filename=t,this.files=e.s._filesCollection,this.options=o,this.writeConcern=d.WriteConcern.fromOptions(o)||e.s.options.writeConcern,this.done=!1,this.id=o.id?o.id:new i.ObjectId,this.chunkSizeBytes=o.chunkSizeBytes||this.bucket.s.options.chunkSizeBytes,this.bufToStore=n.alloc(this.chunkSizeBytes),this.length=0,this.n=0,this.pos=0,this.state={streamEnd:!1,outstandingRequests:0,errored:!1,aborted:!1},null!=o.timeoutMS&&(this.timeoutContext=new c.CSOTTimeoutContext({timeoutMS:o.timeoutMS,serverSelectionTimeoutMS:(0,l.resolveTimeoutOptions)(this.bucket.s.db.client,{}).serverSelectionTimeoutMS}))}_construct(e){if(this.bucket.s.calledOpenUploadStream)return queueMicrotask(e);this.bucket.s.calledOpenUploadStream=!0,async function(e){let t=e.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`);if(null!=await e.files.findOne({},{projection:{_id:1},timeoutMS:t}))return;let o;t=e.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`);const n={timeoutMode:null!=t?s.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:t};try{o=await e.files.listIndexes(n).toArray()}catch(e){if(!(e instanceof a.MongoError&&e.code===a.MONGODB_ERROR_CODES.NamespaceNotFound))throw e;o=[]}o.find((e=>2===Object.keys(e.key).length&&1===e.key.filename&&1===e.key.uploadDate))||(t=e.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`),await e.files.createIndex({filename:1,uploadDate:1},{background:!1,timeoutMS:t})),await async function(e){let t,o;t=e.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`);try{o=await e.chunks.listIndexes({timeoutMode:null!=t?s.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:t}).toArray()}catch(e){if(!(e instanceof a.MongoError&&e.code===a.MONGODB_ERROR_CODES.NamespaceNotFound))throw e;o=[]}const n=!!o.find((e=>2===Object.keys(e.key).length&&1===e.key.files_id&&1===e.key.n));n||(t=e.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`),await e.chunks.createIndex({files_id:1,n:1},{...e.writeConcern,background:!0,unique:!0,timeoutMS:t}))}(e)}(this).then((()=>{this.bucket.s.checkedIndexes=!0,this.bucket.emit("index"),e()}),(t=>{if(t instanceof a.MongoOperationTimeoutError)return h(this,t,e);(0,l.squashError)(t),e()}))}_write(e,t,o){!function(e,t,o,r){if(g(e,r))return;const i=n.isBuffer(t)?t:n.from(t,o);if(e.length+=i.length,e.pos+i.length<e.chunkSizeBytes)return i.copy(e.bufToStore,e.pos),e.pos+=i.length,void queueMicrotask(r);let s=i.length,c=e.chunkSizeBytes-e.pos,l=Math.min(c,i.length),d=0;for(;s>0;){const t=i.length-s;let o;if(i.copy(e.bufToStore,e.pos,t,t+l),e.pos+=l,c-=l,0===c){o=m(e.id,e.n,n.from(e.bufToStore));const t=e.timeoutContext?.remainingTimeMS;if(null!=t&&t<=0)return h(e,new a.MongoOperationTimeoutError(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`),r);if(++e.state.outstandingRequests,++d,g(e,r))return;e.chunks.insertOne(o,{writeConcern:e.writeConcern,timeoutMS:t}).then((()=>{--e.state.outstandingRequests,--d,d||p(e,r)}),(t=>h(e,t,r))),c=e.chunkSizeBytes,e.pos=0,++e.n}s-=l,l=Math.min(c,s)}}(this,e,t,o)}_final(e){if(this.state.streamEnd)return queueMicrotask(e);this.state.streamEnd=!0,function(e,t){if(0===e.pos)return p(e,t);const o=n.alloc(e.pos);e.bufToStore.copy(o,0,0,e.pos);const r=m(e.id,e.n,o);if(g(e,t))return;const i=e.timeoutContext?.remainingTimeMS;if(null!=i&&i<=0)return h(e,new a.MongoOperationTimeoutError(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`),t);++e.state.outstandingRequests,e.chunks.insertOne(r,{writeConcern:e.writeConcern,timeoutMS:i}).then((()=>{--e.state.outstandingRequests,p(e,t)}),(o=>h(e,o,t)))}(this,e)}async abort(){if(this.state.streamEnd)throw new a.MongoAPIError("Cannot abort a stream that has already completed");if(this.state.aborted)throw new a.MongoAPIError("Cannot call abort() on a stream twice");this.state.aborted=!0;const e=this.timeoutContext?.getRemainingTimeMSOrThrow(`Upload timed out after ${this.timeoutContext?.timeoutMS}ms`);await this.chunks.deleteMany({files_id:this.id},{timeoutMS:e})}}function h(e,t,o){e.state.errored?queueMicrotask(o):(e.state.errored=!0,queueMicrotask((()=>o(t))))}function m(e,t,o){return{_id:new i.ObjectId,files_id:e,n:t,data:o}}function p(e,t){if(e.done)return queueMicrotask(t);if(e.state.streamEnd&&0===e.state.outstandingRequests&&!e.state.errored){e.done=!0;const o=function(e,t,o,n,r){const i={_id:e,length:t,chunkSize:o,uploadDate:new Date,filename:n};return r&&(i.metadata=r),i}(e.id,e.length,e.chunkSizeBytes,e.filename,e.options.metadata);if(g(e,t))return;const n=e.timeoutContext?.remainingTimeMS;return null!=n&&n<=0?h(e,new a.MongoOperationTimeoutError(`Upload timed out after ${e.timeoutContext?.timeoutMS}ms`),t):void e.files.insertOne(o,{writeConcern:e.writeConcern,timeoutMS:n}).then((()=>{e.gridFSFile=o,t()}),(o=>h(e,o,t)))}queueMicrotask(t)}function g(e,t){return!!e.state.aborted&&(queueMicrotask((()=>t(new a.MongoAPIError("Stream has been aborted")))),!0)}t.GridFSBucketWriteStream=u},44820:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteResultsMerger=void 0;const n=o(183),r=o(36997),i={acknowledged:!1,insertedCount:0,upsertedCount:0,matchedCount:0,modifiedCount:0,deletedCount:0,insertResults:void 0,updateResults:void 0,deleteResults:void 0};t.ClientBulkWriteResultsMerger=class{static unacknowledged(){return i}constructor(e){this.options=e,this.currentBatchOffset=0,this.writeConcernErrors=[],this.writeErrors=new Map,this.result={acknowledged:!0,insertedCount:0,upsertedCount:0,matchedCount:0,modifiedCount:0,deletedCount:0,insertResults:void 0,updateResults:void 0,deleteResults:void 0},e.verboseResults&&(this.result.insertResults=new Map,this.result.updateResults=new Map,this.result.deleteResults=new Map)}get bulkWriteResult(){return{acknowledged:this.result.acknowledged,insertedCount:this.result.insertedCount,upsertedCount:this.result.upsertedCount,matchedCount:this.result.matchedCount,modifiedCount:this.result.modifiedCount,deletedCount:this.result.deletedCount,insertResults:this.result.insertResults,updateResults:this.result.updateResults,deleteResults:this.result.deleteResults}}async merge(e){let t;try{for await(const t of e)if(1===t.ok)this.options.verboseResults&&this.processDocument(e,t);else{if(this.options.ordered){const e=new r.MongoClientBulkWriteError({message:"Mongo client ordered bulk write encountered a write error."});throw e.writeErrors.set(t.idx+this.currentBatchOffset,{code:t.code,message:t.errmsg}),e.partialResult=this.result,e}this.writeErrors.set(t.idx+this.currentBatchOffset,{code:t.code,message:t.errmsg})}}catch(o){if(!(o instanceof n.MongoWriteConcernError))throw o;{const n=o.result;if(t={insertedCount:n.nInserted,upsertedCount:n.nUpserted,matchedCount:n.nMatched,modifiedCount:n.nModified,deletedCount:n.nDeleted,writeConcernError:n.writeConcernError},this.options.verboseResults&&n.cursor.firstBatch)for(const t of n.cursor.firstBatch)1===t.ok&&this.processDocument(e,t)}}finally{if(e.response){const t=e.response;this.incrementCounts(t)}this.currentBatchOffset+=e.operations.length}if(t){const e=t.writeConcernError;this.incrementCounts(t),this.writeConcernErrors.push({code:e.code,message:e.errmsg})}return this.result}processDocument(e,t){const o=e.operations[t.idx];if("insert"in o&&this.result.insertResults?.set(t.idx+this.currentBatchOffset,{insertedId:o.document._id}),"update"in o){const e={matchedCount:t.n,modifiedCount:t.nModified??0,didUpsert:null!=t.upserted};t.upserted&&(e.upsertedId=t.upserted._id),this.result.updateResults?.set(t.idx+this.currentBatchOffset,e)}"delete"in o&&this.result.deleteResults?.set(t.idx+this.currentBatchOffset,{deletedCount:t.n})}incrementCounts(e){this.result.insertedCount+=e.insertedCount,this.result.upsertedCount+=e.upsertedCount,this.result.matchedCount+=e.matchedCount,this.result.modifiedCount+=e.modifiedCount,this.result.deletedCount+=e.deletedCount}}},45249:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DropDatabaseOperation=t.DropCollectionOperation=void 0,t.dropCollections=async function(e,t,o){const n=a.TimeoutContext.create({session:o.session,serverSelectionTimeoutMS:e.client.s.options.serverSelectionTimeoutMS,waitQueueTimeoutMS:e.client.s.options.waitQueueTimeoutMS,timeoutMS:o.timeoutMS}),r=e.client.s.options.autoEncryption?.encryptedFieldsMap;let s=o.encryptedFields??r?.[`${e.databaseName}.${t}`];if(!s&&r){const r=await e.listCollections({name:t},{nameOnly:!1,session:o.session,timeoutContext:new i.CursorTimeoutContext(n,Symbol())}).toArray();s=r?.[0]?.options?.encryptedFields}if(s){const r=s.escCollection||`enxcol_.${t}.esc`,i=s.ecocCollection||`enxcol_.${t}.ecoc`;for(const t of[r,i]){const r=new u(e,t,o);await(0,l.executeOperation)(e.client,r,n)}}return await(0,l.executeOperation)(e.client,new u(e,t,o),n)};const n=o(183),r=o(72216),i=o(40927),s=o(36997),a=o(33628),c=o(41539),l=o(39131),d=o(28947);class u extends c.CommandOperation{constructor(e,t,o={}){super(e,o),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=o,this.name=t}get commandName(){return"drop"}buildCommandDocument(e,t){return{drop:this.name}}handleOk(e){return!0}handleError(e){if(!(e instanceof n.MongoServerError))throw e;if(Number(e.code)!==s.MONGODB_ERROR_CODES.NamespaceNotFound)throw e;return!1}}t.DropCollectionOperation=u;class h extends c.CommandOperation{constructor(e,t){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=t}get commandName(){return"dropDatabase"}buildCommandDocument(e,t){return{dropDatabase:1}}handleOk(e){return!0}}t.DropDatabaseOperation=h,(0,d.defineAspects)(u,[d.Aspect.WRITE_OPERATION]),(0,d.defineAspects)(h,[d.Aspect.WRITE_OPERATION])},46195:e=>{e.exports={rE:"7.1.1"}},46352:(e,t,o)=>{var n=o(34110).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.ClientEncryption=void 0,t.autoSelectSocketOptions=h;const r=o(77953),i=o(98517),s=o(33628),a=o(30306),c=o(64578),l=o(85744),d=o(8138);class u{static getMongoCrypt(){const e=(0,i.getMongoDBClientEncryption)();if("kModuleError"in e)throw e.kModuleError;return e.MongoCrypt}constructor(e,t){this._client=e,this._proxyOptions=t.proxyOptions??{},this._tlsOptions=t.tlsOptions??{},this._kmsProviders=t.kmsProviders||{};const{timeoutMS:o}=(0,a.resolveTimeoutOptions)(e,t);if(this._timeoutMS=o,this._credentialProviders=t.credentialProviders,t.credentialProviders?.aws&&!(0,l.isEmptyCredentials)("aws",this._kmsProviders))throw new c.MongoCryptInvalidArgumentError("Can only provide a custom AWS credential provider when the state machine is configured for automatic AWS credential fetching");if(null==t.keyVaultNamespace)throw new c.MongoCryptInvalidArgumentError("Missing required option `keyVaultNamespace`");const i={...t,kmsProviders:n.isBuffer(this._kmsProviders)?this._kmsProviders:(0,r.serialize)(this._kmsProviders),errorWrapper:c.defaultErrorWrapper};this._keyVaultNamespace=t.keyVaultNamespace,this._keyVaultClient=t.keyVaultClient||e;const s=u.getMongoCrypt();this._mongoCrypt=new s(i)}async createDataKey(e,t={}){if(t.keyAltNames&&!Array.isArray(t.keyAltNames))throw new c.MongoCryptInvalidArgumentError(`Option "keyAltNames" must be an array of strings, but was of type ${typeof t.keyAltNames}.`);let o,n;t.keyAltNames&&t.keyAltNames.length>0&&(o=t.keyAltNames.map(((e,t)=>{if("string"!=typeof e)throw new c.MongoCryptInvalidArgumentError(`Option "keyAltNames" must be an array of strings, but item at index ${t} was of type ${typeof e}`);return(0,r.serialize)({keyAltName:e})}))),t.keyMaterial&&(n=(0,r.serialize)({keyMaterial:t.keyMaterial}));const i=(0,r.serialize)({provider:e,...t.masterKey}),l=this._mongoCrypt.makeDataKeyContext(i,{keyAltNames:o,keyMaterial:n}),u=new d.StateMachine({proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:h(this._client.s.options)}),m=t?.timeoutContext??s.TimeoutContext.create((0,a.resolveTimeoutOptions)(this._client,{timeoutMS:this._timeoutMS})),p=(0,r.deserialize)(await u.execute(this,l,{timeoutContext:m})),{db:g,collection:f}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace),{insertedId:S}=await this._keyVaultClient.db(g).collection(f).insertOne(p,{writeConcern:{w:"majority"},timeoutMS:m?.csotEnabled()?m?.getRemainingTimeMSOrThrow():void 0});return S}async rewrapManyDataKey(e,t){let o;if(t){const e=Object.assign({provider:t.provider},t.masterKey);o=(0,r.serialize)(e)}const n=(0,r.serialize)(e),i=this._mongoCrypt.makeRewrapManyDataKeyContext(n,o),c=new d.StateMachine({proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:h(this._client.s.options)}),l=s.TimeoutContext.create((0,a.resolveTimeoutOptions)(this._client,{timeoutMS:this._timeoutMS})),{v:u}=(0,r.deserialize)(await c.execute(this,i,{timeoutContext:l}));if(0===u.length)return{};const{db:m,collection:p}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace),g=u.map((e=>({updateOne:{filter:{_id:e._id},update:{$set:{masterKey:e.masterKey,keyMaterial:e.keyMaterial},$currentDate:{updateDate:!0}}}})));return{bulkWriteResult:await this._keyVaultClient.db(m).collection(p).bulkWrite(g,{writeConcern:{w:"majority"},timeoutMS:l.csotEnabled()?l?.remainingTimeMS:void 0})}}async deleteKey(e){const{db:t,collection:o}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return await this._keyVaultClient.db(t).collection(o).deleteOne({_id:e},{writeConcern:{w:"majority"},timeoutMS:this._timeoutMS})}getKeys(){const{db:e,collection:t}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return this._keyVaultClient.db(e).collection(t).find({},{readConcern:{level:"majority"},timeoutMS:this._timeoutMS})}async getKey(e){const{db:t,collection:o}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return await this._keyVaultClient.db(t).collection(o).findOne({_id:e},{readConcern:{level:"majority"},timeoutMS:this._timeoutMS})}async getKeyByAltName(e){const{db:t,collection:o}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return await this._keyVaultClient.db(t).collection(o).findOne({keyAltNames:e},{readConcern:{level:"majority"},timeoutMS:this._timeoutMS})}async addKeyAltName(e,t){const{db:o,collection:n}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace);return await this._keyVaultClient.db(o).collection(n).findOneAndUpdate({_id:e},{$addToSet:{keyAltNames:t}},{writeConcern:{w:"majority"},returnDocument:"before",timeoutMS:this._timeoutMS})}async removeKeyAltName(e,t){const{db:o,collection:n}=a.MongoDBCollectionNamespace.fromString(this._keyVaultNamespace),r=[{$set:{keyAltNames:{$cond:[{$eq:["$keyAltNames",[t]]},"$$REMOVE",{$filter:{input:"$keyAltNames",cond:{$ne:["$$this",t]}}}]}}}];return await this._keyVaultClient.db(o).collection(n).findOneAndUpdate({_id:e},r,{writeConcern:{w:"majority"},returnDocument:"before",timeoutMS:this._timeoutMS})}async createEncryptedCollection(e,t,o){const{provider:n,masterKey:r,createCollectionOptions:{encryptedFields:{...i},...l}}=o,d=null!=this._timeoutMS?s.TimeoutContext.create((0,a.resolveTimeoutOptions)(this._client,{timeoutMS:this._timeoutMS})):void 0;if(Array.isArray(i.fields)){const e=i.fields.map((async e=>null==e||"object"!=typeof e||null!=e.keyId?e:{...e,keyId:await this.createDataKey(n,{masterKey:r,timeoutContext:d?.csotEnabled()?d?.clone():void 0})})),t=await Promise.allSettled(e);i.fields=t.map(((e,t)=>"fulfilled"===e.status?e.value:i.fields[t]));const o=t.find((e=>"rejected"===e.status));if(null!=o)throw new c.MongoCryptCreateDataKeyError(i,{cause:o.reason})}try{return{collection:await e.createCollection(t,{...l,encryptedFields:i,timeoutMS:d?.csotEnabled()?d?.getRemainingTimeMSOrThrow():void 0}),encryptedFields:i}}catch(e){throw new c.MongoCryptCreateEncryptedCollectionError(i,{cause:e})}}async encrypt(e,t){return await this._encrypt(e,!1,t)}async encryptExpression(e,t){return await this._encrypt(e,!0,t)}async decrypt(e){const t=(0,r.serialize)({v:e}),o=this._mongoCrypt.makeExplicitDecryptionContext(t),n=new d.StateMachine({proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:h(this._client.s.options)}),i=null!=this._timeoutMS?s.TimeoutContext.create((0,a.resolveTimeoutOptions)(this._client,{timeoutMS:this._timeoutMS})):void 0,{v:c}=(0,r.deserialize)(await n.execute(this,o,{timeoutContext:i}));return c}async askForKMSCredentials(){return await(0,l.refreshKMSCredentials)(this._kmsProviders,this._credentialProviders)}static get libmongocryptVersion(){return u.getMongoCrypt().libmongocryptVersion}async _encrypt(e,t,o){const{algorithm:n,keyId:i,keyAltName:l,contentionFactor:u,queryType:m,rangeOptions:p,textOptions:g}=o,f={expressionMode:t,algorithm:n};if(i&&(f.keyId=i.buffer),l){if(i)throw new c.MongoCryptInvalidArgumentError('"options" cannot contain both "keyId" and "keyAltName"');if("string"!=typeof l)throw new c.MongoCryptInvalidArgumentError('"options.keyAltName" must be of type string, but was of type '+typeof l);f.keyAltName=(0,r.serialize)({keyAltName:l})}"number"!=typeof u&&"bigint"!=typeof u||(f.contentionFactor=u),"string"==typeof m&&(f.queryType=m),"object"==typeof p&&(f.rangeOptions=(0,r.serialize)(p)),"object"==typeof g&&(f.textOptions=(0,r.serialize)(g));const S=(0,r.serialize)({v:e}),E=new d.StateMachine({proxyOptions:this._proxyOptions,tlsOptions:this._tlsOptions,socketOptions:h(this._client.s.options)}),y=this._mongoCrypt.makeExplicitEncryptionContext(S,f),b=null!=this._timeoutMS?s.TimeoutContext.create((0,a.resolveTimeoutOptions)(this._client,{timeoutMS:this._timeoutMS})):void 0,{v:O}=(0,r.deserialize)(await E.execute(this,y,{timeoutContext:b}));return O}}function h(e){const t={autoSelectFamily:!0};return"autoSelectFamily"in e&&(t.autoSelectFamily=e.autoSelectFamily),"autoSelectFamilyAttemptTimeout"in e&&(t.autoSelectFamilyAttemptTimeout=e.autoSelectFamilyAttemptTimeout),t}t.ClientEncryption=u},48384:function(e,t,o){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.coerceObject=function(e){return t=>{switch(typeof t){case"string":return e.parse(JSON.parse(t));case"object":return t;default:return null}}},t.coerceIfBoolean=function(e){return"string"==typeof e?"true"===e||"false"!==e&&e:e},t.coerceIfFalse=function(e){return void 0===e||""===e?null:"string"==typeof e?"false"!==e&&e:e},t.unwrapType=function(e){i(e);let t=r.default.clone(e);for(;t instanceof r.default.ZodOptional||t instanceof r.default.ZodDefault||t instanceof r.default.ZodNullable||t instanceof r.default.ZodPipe;)if(t instanceof r.default.ZodPipe){const e=t.def.out;i(e),t=e}else{const e=t.unwrap();i(e),t=e}return t};const r=n(o(99539));function i(e){if(!(e instanceof r.default.ZodType))throw new Error(`Unknown schema field type: ${e&&"object"==typeof e?e.constructor.name:typeof e}`)}},48570:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.X509=void 0;const n=o(36997),r=o(30306),i=o(68950);class s extends i.AuthProvider{async prepare(e,t){const{credentials:o}=t;if(!o)throw new n.MongoMissingCredentialsError("AuthContext must provide credentials.");return{...e,speculativeAuthenticate:a(o)}}async auth(e){const t=e.connection,o=e.credentials;if(!o)throw new n.MongoMissingCredentialsError("AuthContext must provide credentials.");const i=e.response;i?.speculativeAuthenticate||await t.command((0,r.ns)("$external.$cmd"),a(o),void 0)}}function a(e){const t={authenticate:1,mechanism:"MONGODB-X509"};return e.username&&(t.user=e.username),t}t.X509=s},49879:(e,t,o)=>{var n=o(34110).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.GridFSBucketReadStream=void 0;const r=o(64371),i=o(40927),s=o(36997),a=o(33628);class c extends r.Readable{static{this.FILE="file"}constructor(e,t,o,n,r){super({emitClose:!0}),this.s={bytesToTrim:0,bytesToSkip:0,bytesRead:0,chunks:e,expected:0,files:t,filter:n,init:!1,expectedEnd:0,options:{start:0,end:0,...r},readPreference:o,timeoutContext:null!=r?.timeoutMS?new a.CSOTTimeoutContext({timeoutMS:r.timeoutMS,serverSelectionTimeoutMS:0}):void 0}}_read(){this.destroyed||function(e,t){if(e.s.file)return t();e.s.init||(function(e){const t={};e.s.readPreference&&(t.readPreference=e.s.readPreference),e.s.options&&e.s.options.sort&&(t.sort=e.s.options.sort),e.s.options&&e.s.options.skip&&(t.skip=e.s.options.skip);let o;try{o=e.s.timeoutContext?.getRemainingTimeMSOrThrow(`Download timed out after ${e.s.timeoutContext?.timeoutMS}ms`)}catch(t){return void(e.destroyed||e.destroy(t))}t.timeoutMS=o,e.s.files.findOne(e.s.filter,t).then((t=>{if(e.destroyed)return;if(!t){const t=`FileNotFound: file ${e.s.filter._id?e.s.filter._id.toString():e.s.filter.filename} was not found`,o=new s.MongoRuntimeError(t);return o.code="ENOENT",e.destroy(o)}if(t.length<=0)return void e.push(null);if(e.destroyed)return void e.destroy();try{e.s.bytesToSkip=function(e,t,o){if(o&&null!=o.start){if(o.start>t.length)throw new s.MongoInvalidArgumentError(`Stream start (${o.start}) must not be more than the length of the file (${t.length})`);if(o.start<0)throw new s.MongoInvalidArgumentError(`Stream start (${o.start}) must not be negative`);if(null!=o.end&&o.end<o.start)throw new s.MongoInvalidArgumentError(`Stream start (${o.start}) must not be greater than stream end (${o.end})`);return e.s.bytesRead=Math.floor(o.start/t.chunkSize)*t.chunkSize,e.s.expected=Math.floor(o.start/t.chunkSize),o.start-e.s.bytesRead}throw new s.MongoInvalidArgumentError("Start option must be defined")}(e,t,e.s.options)}catch(t){return e.destroy(t)}const o={files_id:t._id};if(e.s.options&&null!=e.s.options.start){const n=Math.floor(e.s.options.start/t.chunkSize);n>0&&(o.n={$gte:n})}let n;try{n=e.s.timeoutContext?.getRemainingTimeMSOrThrow(`Download timed out after ${e.s.timeoutContext?.timeoutMS}ms`)}catch(t){return e.destroy(t)}e.s.cursor=e.s.chunks.find(o,{timeoutMode:null!=e.s.options.timeoutMS?i.CursorTimeoutMode.LIFETIME:void 0,timeoutMS:n}).sort({n:1}),e.s.readPreference&&e.s.cursor.withReadPreference(e.s.readPreference),e.s.expectedEnd=Math.ceil(t.length/t.chunkSize),e.s.file=t;try{e.s.bytesToTrim=function(e,t,o,n){if(n&&null!=n.end){if(n.end>t.length)throw new s.MongoInvalidArgumentError(`Stream end (${n.end}) must not be more than the length of the file (${t.length})`);if(null==n.start||n.start<0)throw new s.MongoInvalidArgumentError(`Stream end (${n.end}) must not be negative`);const r=null!=n.start?Math.floor(n.start/t.chunkSize):0;return o.limit(Math.ceil(n.end/t.chunkSize)-r),e.s.expectedEnd=Math.ceil(n.end/t.chunkSize),Math.ceil(n.end/t.chunkSize)*t.chunkSize-n.end}throw new s.MongoInvalidArgumentError("End option must be defined")}(e,t,e.s.cursor,e.s.options)}catch(t){return e.destroy(t)}e.emit(c.FILE,t)}),(t=>{e.destroyed||e.destroy(t)}))}(e),e.s.init=!0),e.once("file",(()=>{t()}))}(this,(()=>function(e){if(e.destroyed)return;if(!e.s.cursor)return;if(!e.s.file)return;e.s.cursor.next().then((t=>{if(e.destroyed)return;if(!t)return e.push(null),void e.s.cursor?.close().then(void 0,(t=>e.destroy(t)));if(!e.s.file)return;const o=e.s.file.length-e.s.bytesRead,r=e.s.expected++,i=Math.min(e.s.file.chunkSize,o);if(t.n>r)return e.destroy(new s.MongoGridFSChunkError(`ChunkIsMissing: Got unexpected n: ${t.n}, expected: ${r}`));if(t.n<r)return e.destroy(new s.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${t.n}, expected: ${r}`));let a=n.isBuffer(t.data)?t.data:t.data.buffer;if(a.byteLength!==i)return o<=0?e.destroy(new s.MongoGridFSChunkError(`ExtraChunk: Got unexpected n: ${t.n}, expected file length ${e.s.file.length} bytes but already read ${e.s.bytesRead} bytes`)):e.destroy(new s.MongoGridFSChunkError(`ChunkIsWrongSize: Got unexpected length: ${a.byteLength}, expected: ${i}`));if(e.s.bytesRead+=a.byteLength,0===a.byteLength)return e.push(null);let c=null,l=null;null!=e.s.bytesToSkip&&(c=e.s.bytesToSkip,e.s.bytesToSkip=0);const d=r===e.s.expectedEnd-1,u=e.s.options.end-e.s.bytesToSkip;d&&null!=e.s.bytesToTrim?l=e.s.file.chunkSize-e.s.bytesToTrim:e.s.options.end&&u<t.data.byteLength&&(l=u),null==c&&null==l||(a=a.slice(c||0,l||a.byteLength)),e.push(a)}),(t=>{e.destroyed||e.destroy(t)}))}(this)))}start(e=0){return l(this),this.s.options.start=e,this}end(e=0){return l(this),this.s.options.end=e,this}async abort(){this.push(null),this.destroy();const e=this.s.timeoutContext?.getRemainingTimeMSOrThrow();await(this.s.cursor?.close({timeoutMS:e}))}}function l(e){if(e.s.init)throw new s.MongoGridFSStreamError("Options cannot be changed after the stream is initialized")}t.GridFSBucketReadStream=c},50558:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CallbackWorkflow=t.AUTOMATED_TIMEOUT_MS=t.HUMAN_TIMEOUT_MS=void 0;const n=o(31713),r=o(36997),i=o(30306),s=o(28777);t.HUMAN_TIMEOUT_MS=3e5,t.AUTOMATED_TIMEOUT_MS=6e4;const a=["accessToken","expiresInSeconds","refreshToken"];t.CallbackWorkflow=class{constructor(e,t){this.cache=e,this.callback=this.withLock(t),this.lastExecutionTime=Date.now()-100}async speculativeAuth(e,t){if(this.cache.hasAccessToken){const o=this.cache.getAccessToken();e.accessToken=o;const n=(0,s.finishCommandDocument)(o);return n.db=t.source,{speculativeAuthenticate:n}}return{}}async reauthenticate(e,t){this.cache.hasAccessToken&&(e.accessToken===this.cache.getAccessToken()?(this.cache.removeAccessToken(),delete e.accessToken):e.accessToken=this.cache.getAccessToken()),await this.execute(e,t)}async startAuthentication(e,t,o){let n;return n=o?.speculativeAuthenticate?o.speculativeAuthenticate:await e.command((0,i.ns)(t.source),(0,s.startCommandDocument)(t),void 0),n}async finishAuthentication(e,t,o,n){await e.command((0,i.ns)(t.source),(0,s.finishCommandDocument)(o,n),void 0)}async executeAndValidateCallback(e){const t=await this.callback(e);if(null==(o=t)||"object"!=typeof o||!("accessToken"in o)||!Object.getOwnPropertyNames(o).every((e=>a.includes(e))))throw new r.MongoMissingCredentialsError("User provided OIDC callbacks must return a valid object with an accessToken.");var o;return t}withLock(e){let t=Promise.resolve();return async o=>(await t,t=t.catch((()=>null)).then((async()=>{const t=Date.now()-this.lastExecutionTime;return t<=100&&await(0,n.setTimeout)(100-t,{signal:o.timeoutContext}),this.lastExecutionTime=Date.now(),await e(o)})),await t)}}},50700:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChangeStreamCursor=void 0;const n=o(53373),r=o(34842),i=o(86065),s=o(39131),a=o(30306),c=o(40927);class l extends c.AbstractCursor{constructor(e,t,o=[],n={}){super(e,t,{...n,tailable:!0,awaitData:!0}),this.pipeline=o,this.changeStreamCursorOptions=n,this._resumeToken=null,this.startAtOperationTime=n.startAtOperationTime??null,n.startAfter?this.resumeToken=n.startAfter:n.resumeAfter&&(this.resumeToken=n.resumeAfter)}set resumeToken(e){this._resumeToken=e,this.emit(n.ChangeStream.RESUME_TOKEN_CHANGED,e)}get resumeToken(){return this._resumeToken}get resumeOptions(){const e={...this.changeStreamCursorOptions};for(const t of["resumeAfter","startAfter","startAtOperationTime"])delete e[t];return null!=this.resumeToken?this.changeStreamCursorOptions.startAfter&&!this.hasReceived?e.startAfter=this.resumeToken:e.resumeAfter=this.resumeToken:null!=this.startAtOperationTime&&(e.startAtOperationTime=this.startAtOperationTime),e}cacheResumeToken(e){0===this.bufferedCount()&&this.postBatchResumeToken?this.resumeToken=this.postBatchResumeToken:this.resumeToken=e,this.hasReceived=!0}_processBatch(e){const{postBatchResumeToken:t}=e;t&&(this.postBatchResumeToken=t,0===e.batchSize&&(this.resumeToken=t))}clone(){return new l(this.client,this.namespace,this.pipeline,{...this.cursorOptions})}async _initialize(e){const t=new i.AggregateOperation(this.namespace,this.pipeline,{...this.cursorOptions,...this.changeStreamCursorOptions,session:e}),o=await(0,s.executeOperation)(e.client,t,this.timeoutContext),n=t.server;return this.maxWireVersion=(0,a.maxWireVersion)(n),null==this.startAtOperationTime&&null==this.changeStreamCursorOptions.resumeAfter&&null==this.changeStreamCursorOptions.startAfter&&(this.startAtOperationTime=o.operationTime),this._processBatch(o),this.emit(r.INIT,o),this.emit(r.RESPONSE),{server:n,session:e,response:o}}async getMore(){const e=await super.getMore();return this.maxWireVersion=(0,a.maxWireVersion)(this.server),this._processBatch(e),this.emit(n.ChangeStream.MORE,e),this.emit(n.ChangeStream.RESPONSE),e}}t.ChangeStreamCursor=l},51499:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UpdateSearchIndexOperation=void 0;const n=o(72216),r=o(28947);class i extends r.AbstractOperation{constructor(e,t,o){super(),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.collection=e,this.name=t,this.definition=o,this.ns=e.fullNamespace}get commandName(){return"updateSearchIndex"}buildCommand(e,t){return{updateSearchIndex:this.collection.fullNamespace.collection,name:this.name,definition:this.definition}}handleOk(e){}buildOptions(e){return{session:this.session,timeoutContext:e}}}t.UpdateSearchIndexOperation=i},51641:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.aws4Sign=async function(e,t){const o=e.date.toISOString().replace(/[:-]|\.\d{3}/g,""),a=o.substring(0,8),c=e.method,l=e.path,d=new Headers({"content-length":s(e.headers["Content-Length"]),"content-type":s(e.headers["Content-Type"]),host:s(e.host),"x-amz-date":s(o),"x-mongodb-gs2-cb-flag":s(e.headers["X-MongoDB-GS2-CB-Flag"]),"x-mongodb-server-nonce":s(e.headers["X-MongoDB-Server-Nonce"])});"sessionToken"in t&&t.sessionToken&&d.append("x-amz-security-token",s(t.sessionToken));const u=Array.from(d.entries()).map((([e,t])=>`${e.toLowerCase()}:${t}`)).sort().join("\n"),h=Array.from(d.keys()).map((e=>e.toLowerCase())).sort().join(";"),m=[c,l,"",u+"\n",h,await r(e.body)].join("\n"),p=await r(m),g=`${a}/${e.region}/${e.service}/aws4_request`,f=["AWS4-HMAC-SHA256",o,g,p].join("\n"),S=await i("AWS4"+t.secretAccessKey,a),E=await i(S,e.region),y=await i(E,e.service),b=await i(y,"aws4_request"),O=await i(b,f),C=n.BSON.onDemand.ByteUtils.toHex(O);return{Authorization:["AWS4-HMAC-SHA256 Credential="+t.accessKeyId+"/"+g,"SignedHeaders="+h,"Signature="+C].join(", "),"X-Amz-Date":o}};const n=o(77953),r=async e=>{const t=a(e),o=await crypto.subtle.digest("SHA-256",t);return n.BSON.onDemand.ByteUtils.toHex(new Uint8Array(o))},i=async(e,t)=>{let o;o="string"==typeof e?a(e):e;const n=await crypto.subtle.importKey("raw",o,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),r=a(t),i=await crypto.subtle.sign("HMAC",n,r);return new Uint8Array(i)},s=e=>e.toString().trim().replace(/\s+/g," ");function a(e){const t=new Uint8Array(n.BSON.onDemand.ByteUtils.utf8ByteLength(e));return n.BSON.onDemand.ByteUtils.encodeUTF8Into(t,e,0),t}},52859:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_OPTIONS=t.OPTIONS=void 0,t.resolveSRVRecord=async function(e){if("string"!=typeof e.srvHost)throw new u.MongoAPIError('Option "srvHost" must not be empty');const t=e.srvHost,o=w(t);o.then(void 0,S.squashError);const n=`_${e.srvServiceName}._tcp.${t}`,r=await T(n);if(0===r.length)throw new u.MongoAPIError("No addresses found at host");for(const{name:e}of r)(0,S.checkParentDomainMatch)(e,t);const i=r.map((e=>S.HostAddress.fromString(`${e.name}:${e.port??27017}`)));let l;N(i,e,!0);try{l=await o}catch(e){if("ENODATA"!==e.code&&"ENOTFOUND"!==e.code)throw e;return i}if(l.length>1)throw new u.MongoParseError("Multiple text records not allowed");const d=new s.URLSearchParams(l[0].join(""));if([...d.keys()].some((e=>!y.includes(e))))throw new u.MongoParseError(`Text record may only set any of: ${y.join(", ")}`);if(y.some((e=>""===d.get(e))))throw new u.MongoParseError("Cannot have empty URI params in DNS TXT Record");const h=d.get("authSource")??void 0,m=d.get("replicaSet")??void 0,p=d.get("loadBalanced")??void 0;if(!e.userSpecifiedAuthSource&&h&&e.credentials&&!c.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(e.credentials.mechanism)&&(e.credentials=a.MongoCredentials.merge(e.credentials,{source:h})),!e.userSpecifiedReplicaSet&&m&&(e.replicaSet=m),"true"===p&&(e.loadBalanced=!0),e.replicaSet&&e.srvMaxHosts>0)throw new u.MongoParseError("Cannot combine replicaSet option with srvMaxHosts");return N(i,e,!0),i},t.parseOptions=function(e,o=void 0,n={}){if(null==o||o instanceof h.MongoClient||(n=o,o=void 0),n.useBigInt64&&"boolean"==typeof n.promoteLongs&&!n.promoteLongs)throw new u.MongoAPIError("Must request either bigint or Long for int64 deserialization");if(n.useBigInt64&&"boolean"==typeof n.promoteValues&&!n.promoteValues)throw new u.MongoAPIError("Must request either bigint or Long for int64 deserialization");const s=new r.default(e),{hosts:l,isSRV:p}=s,g=Object.create(null);g.hosts=p?[]:l.map(S.HostAddress.fromString);const f=new I;if("/"!==s.pathname&&""!==s.pathname){const e=decodeURIComponent("/"===s.pathname[0]?s.pathname.slice(1):s.pathname);e&&f.set("dbName",[e])}if(""!==s.username){const e={username:decodeURIComponent(s.username)};"string"==typeof s.password&&(e.password=decodeURIComponent(s.password)),f.set("auth",[e])}for(const e of s.searchParams.keys()){const t=s.searchParams.getAll(e),o=/readPreferenceTags/i.test(e);if(!o&&t.length>1)throw new u.MongoInvalidArgumentError(`URI option "${e}" cannot appear more than once in the connection string`);if(!o&&t.includes(""))throw new u.MongoAPIError(`URI option "${e}" cannot be specified with no value`);f.has(e)||f.set(e,t)}const E=new I(Object.entries(n).filter((([,e])=>null!=e)));if(f.has("serverApi"))throw new u.MongoParseError("URI cannot contain `serverApi`, it can only be passed to the client");const y=f.get("authMechanismProperties");if(y)for(const e of y)if(/(^|,)ALLOWED_HOSTS:/.test(e))throw new u.MongoParseError("Auth mechanism property ALLOWED_HOSTS is not allowed in the connection string.");if(E.has("loadBalanced"))throw new u.MongoParseError("loadBalanced is only a valid option in the URI");const b=new I,O=new Set([...f.keys(),...E.keys()]);for(const e of O){const t=[],o=E.get(e);null!=o&&t.push(o);const n=f.get(e)??[];t.push(...n),b.set(e,t)}if(b.has("tls")||b.has("ssl")){const e=(b.get("tls")||[]).concat(b.get("ssl")||[]).map(v.bind(null,"tls/ssl"));if(1!==new Set(e).size)throw new u.MongoParseError("All values of tls/ssl must be the same.")}!function(e){if(!e)return;const t=(t,o)=>{if(e.has(t)&&e.has(o))throw new u.MongoAPIError(`The '${t}' option cannot be used with the '${o}' option`)};t("tlsInsecure","tlsAllowInvalidCertificates"),t("tlsInsecure","tlsAllowInvalidHostnames")}(b);const C=(0,S.setDifference)(O,Array.from(Object.keys(t.OPTIONS)).map((e=>e.toLowerCase())));if(0!==C.size){const e=C.size>1?"options":"option",t=C.size>1?"are":"is";throw new u.MongoParseError(`${e} ${Array.from(C).join(", ")} ${t} not supported`)}for(const[e,o]of Object.entries(t.OPTIONS)){const n=b.get(e);if(n&&0!==n.length){const{deprecated:t}=o;if(t){const o="string"==typeof t?`: ${t}`:"";(0,S.emitWarning)(`${e} is a deprecated option${o}`)}x(g,e,o,n)}else t.DEFAULT_OPTIONS.has(e)&&x(g,e,o,[t.DEFAULT_OPTIONS.get(e)])}if(g.credentials){const e=g.credentials.mechanism===c.AuthMechanism.MONGODB_GSSAPI,t=g.credentials.mechanism===c.AuthMechanism.MONGODB_X509,o=g.credentials.mechanism===c.AuthMechanism.MONGODB_AWS,n=g.credentials.mechanism===c.AuthMechanism.MONGODB_OIDC;if((e||t)&&b.has("authSource")&&"$external"!==g.credentials.source)throw new u.MongoParseError(`authMechanism ${g.credentials.mechanism} requires an authSource of '$external'`);if(e||t||o||n||!g.dbName||b.has("authSource")||(g.credentials=a.MongoCredentials.merge(g.credentials,{source:g.dbName})),o){const{username:e,password:t}=g.credentials;if(e||t)throw new u.MongoAPIError("username and password cannot be provided when using MONGODB-AWS. Credentials must be provided in a manner that can be read by the AWS SDK.");if(g.credentials.mechanismProperties.AWS_SESSION_TOKEN)throw new u.MongoAPIError("AWS_SESSION_TOKEN cannot be provided when using MONGODB-AWS. Credentials must be provided in a manner that can be read by the AWS SDK.")}g.credentials.validate(),""===g.credentials.password&&""===g.credentials.username&&g.credentials.mechanism===c.AuthMechanism.MONGODB_DEFAULT&&0===Object.keys(g.credentials.mechanismProperties).length&&delete g.credentials}if(g.dbName||(g.dbName="test"),N(l,g,p),o&&g.autoEncryption&&(d.Encrypter.checkForMongoCrypt(),g.encrypter=new d.Encrypter(o,e,n),g.autoEncrypter=g.encrypter.autoEncrypter),g.userSpecifiedAuthSource=E.has("authSource")||f.has("authSource"),g.userSpecifiedReplicaSet=E.has("replicaSet")||f.has("replicaSet"),p){if(g.srvHost=l[0],g.directConnection)throw new u.MongoAPIError("SRV URI does not support directConnection");if(g.srvMaxHosts>0&&"string"==typeof g.replicaSet)throw new u.MongoParseError("Cannot use srvMaxHosts option with replicaSet");const e=!E.has("tls")&&!f.has("tls"),t=!E.has("ssl")&&!f.has("ssl");e&&t&&(g.tls=!0)}else if(f.has("srvMaxHosts")||E.has("srvMaxHosts")||f.has("srvServiceName")||E.has("srvServiceName"))throw new u.MongoParseError("Cannot use srvMaxHosts or srvServiceName with a non-srv connection string");if(g.directConnection&&1!==g.hosts.length)throw new u.MongoParseError("directConnection option requires exactly one host");if(!g.proxyHost&&(g.proxyPort||g.proxyUsername||g.proxyPassword))throw new u.MongoParseError("Must specify proxyHost if other proxy options are passed");if(g.proxyUsername&&!g.proxyPassword||!g.proxyUsername&&g.proxyPassword)throw new u.MongoParseError("Can only specify both of proxy username/password or neither");if(["proxyHost","proxyPort","proxyUsername","proxyPassword"].map((e=>f.get(e)??[])).some((e=>e.length>1)))throw new u.MongoParseError("Proxy options cannot be specified multiple times in the connection string");return g.mongoLoggerOptions=m.MongoLogger.resolveOptions({MONGODB_LOG_COMMAND:i.env.MONGODB_LOG_COMMAND,MONGODB_LOG_TOPOLOGY:i.env.MONGODB_LOG_TOPOLOGY,MONGODB_LOG_SERVER_SELECTION:i.env.MONGODB_LOG_SERVER_SELECTION,MONGODB_LOG_CONNECTION:i.env.MONGODB_LOG_CONNECTION,MONGODB_LOG_CLIENT:i.env.MONGODB_LOG_CLIENT,MONGODB_LOG_ALL:i.env.MONGODB_LOG_ALL,MONGODB_LOG_MAX_DOCUMENT_LENGTH:i.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH,MONGODB_LOG_PATH:i.env.MONGODB_LOG_PATH},{mongodbLogPath:g.mongodbLogPath,mongodbLogComponentSeverities:g.mongodbLogComponentSeverities,mongodbLogMaxDocumentLength:g.mongodbLogMaxDocumentLength}),g};const n=o(79498),r=o(42344),i=o(15088),s=o(21655),a=o(32985),c=o(65070),l=o(73738),d=o(17817),u=o(36997),h=o(88757),m=o(60866),p=o(86552),g=o(74891),f=o(93323),S=o(30306),E=o(71259),y=["authSource","replicaSet","loadBalanced"],b="loadBalanced option only supported with a single host in the URI",O="loadBalanced option not supported with a replicaSet option",C="loadBalanced option not supported when directConnection is provided";function M(e){return async function(t){try{return await n.promises[e](t)}catch(o){if(o.code===n.TIMEOUT)return await n.promises[e](t);throw o}}}const T=M("resolveSrv"),w=M("resolveTxt");function v(e,t){if("boolean"==typeof t)return t;switch(t){case"true":return!0;case"false":return!1;default:throw new u.MongoParseError(`${e} must be either "true" or "false"`)}}function R(e,t){const o=(0,S.parseInteger)(t);if(null!=o)return o;throw new u.MongoParseError(`Expected ${e} to be stringified int value, got: ${t}`)}function A(e,t){const o=R(e,t);if(o<0)throw new u.MongoParseError(`${e} can only be a positive int value, got: ${t}`);return o}function*_(e){if(""===e)return;const t=e.split(",");for(const e of t){const[t,o]=e.split(/:(.*)/);if(null==o)throw new u.MongoParseError("Cannot have undefined values in key value pairs");yield[t,o]}}class I extends Map{constructor(e=[]){super(e.map((([e,t])=>[e.toLowerCase(),t])))}has(e){return super.has(e.toLowerCase())}get(e){return super.get(e.toLowerCase())}set(e,t){return super.set(e.toLowerCase(),t)}delete(e){return super.delete(e.toLowerCase())}}function N(e,t,o){if(t.loadBalanced){if(e.length>1)throw new u.MongoParseError(b);if(t.replicaSet)throw new u.MongoParseError(O);if(t.directConnection)throw new u.MongoParseError(C);if(o&&t.srvMaxHosts>0)throw new u.MongoParseError("Cannot limit srv hosts with loadBalanced enabled")}}function x(e,t,o,n){const{target:r,type:i,transform:s}=o,a=r??t;switch(i){case"boolean":e[a]=v(a,n[0]);break;case"int":e[a]=R(a,n[0]);break;case"uint":e[a]=A(a,n[0]);break;case"string":if(null==n[0])break;e[a]=String(n[0]);break;case"record":if(!(0,S.isRecord)(n[0]))throw new u.MongoParseError(`${a} must be an object`);e[a]=n[0];break;case"any":e[a]=n[0];break;default:{if(!s)throw new u.MongoParseError("Descriptors missing a type must define a transform");const t=s({name:a,options:e,values:n});e[a]=t;break}}}t.OPTIONS={appName:{type:"string"},auth:{target:"credentials",transform({name:e,options:t,values:[o]}){if(!(0,S.isRecord)(o,["username","password"]))throw new u.MongoParseError(`${e} must be an object with 'username' and 'password' properties`);return a.MongoCredentials.merge(t.credentials,{username:o.username,password:o.password})}},authMechanism:{target:"credentials",transform({options:e,values:[t]}){const o=Object.values(c.AuthMechanism),[n]=o.filter((e=>e.match(RegExp(String.raw`\b${t}\b`,"i"))));if(!n)throw new u.MongoParseError(`authMechanism one of ${o}, got ${t}`);let r=e.credentials?.source;(n===c.AuthMechanism.MONGODB_PLAIN||c.AUTH_MECHS_AUTH_SRC_EXTERNAL.has(n))&&(r="$external");let i=e.credentials?.password;return n===c.AuthMechanism.MONGODB_X509&&""===i&&(i=void 0),a.MongoCredentials.merge(e.credentials,{mechanism:n,source:r,password:i})}},authMechanismProperties:{target:"credentials",transform({options:e,values:t}){let o=Object.create(null);for(const e of t)if("string"==typeof e)for(const[t,n]of _(e))try{o[t]=v(t,n)}catch{o[t]=n}else{if(!(0,S.isRecord)(e))throw new u.MongoParseError("AuthMechanismProperties must be an object");o={...e}}return a.MongoCredentials.merge(e.credentials,{mechanismProperties:o})}},authSource:{target:"credentials",transform({options:e,values:[t]}){const o=String(t);return a.MongoCredentials.merge(e.credentials,{source:o})}},autoEncryption:{type:"record"},autoSelectFamily:{type:"boolean",default:!0},autoSelectFamilyAttemptTimeout:{type:"uint"},bsonRegExp:{type:"boolean"},serverApi:{target:"serverApi",transform({values:[e]}){const t="string"==typeof e?{version:e}:e,o=t&&t.version;if(!o)throw new u.MongoParseError(`Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values(h.ServerApiVersion).join('", "')}"]`);if(!Object.values(h.ServerApiVersion).some((e=>e===o)))throw new u.MongoParseError(`Invalid server API version=${o}; must be in the following enum: ["${Object.values(h.ServerApiVersion).join('", "')}"]`);return t}},checkKeys:{type:"boolean"},compressors:{default:"none",target:"compressors",transform({values:e}){const t=new Set;for(const o of e){const e="string"==typeof o?o.split(","):o;if(!Array.isArray(e))throw new u.MongoInvalidArgumentError("compressors must be an array or a comma-delimited list of strings");for(const o of e){if(!Object.keys(l.Compressor).includes(String(o)))throw new u.MongoInvalidArgumentError(`${o} is not a valid compression mechanism. Must be one of: ${Object.keys(l.Compressor)}.`);t.add(String(o))}}return[...t]}},connectTimeoutMS:{default:3e4,type:"uint"},dbName:{type:"string"},directConnection:{default:!1,type:"boolean"},driverInfo:{default:{},type:"record"},enableUtf8Validation:{type:"boolean",default:!0},family:{transform({name:e,values:[t]}){const o=R(e,t);if(4===o||6===o)return o;throw new u.MongoParseError(`Option 'family' must be 4 or 6 got ${o}.`)}},fieldsAsRaw:{type:"record"},forceServerObjectId:{default:!1,type:"boolean"},fsync:{deprecated:"Please use journal instead",target:"writeConcern",transform({name:e,options:t,values:[o]}){const n=E.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,fsync:v(e,o)}});if(!n)throw new u.MongoParseError(`Unable to make a writeConcern from fsync=${o}`);return n}},heartbeatFrequencyMS:{default:1e4,type:"uint"},ignoreUndefined:{type:"boolean"},j:{deprecated:"Please use journal instead",target:"writeConcern",transform({name:e,options:t,values:[o]}){const n=E.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,journal:v(e,o)}});if(!n)throw new u.MongoParseError(`Unable to make a writeConcern from journal=${o}`);return n}},journal:{target:"writeConcern",transform({name:e,options:t,values:[o]}){const n=E.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,journal:v(e,o)}});if(!n)throw new u.MongoParseError(`Unable to make a writeConcern from journal=${o}`);return n}},loadBalanced:{default:!1,type:"boolean"},localThresholdMS:{default:15,type:"uint"},maxConnecting:{default:2,transform({name:e,values:[t]}){const o=A(e,t);if(0===o)throw new u.MongoInvalidArgumentError("maxConnecting must be > 0 if specified");return o}},maxIdleTimeMS:{default:0,type:"uint"},maxPoolSize:{default:100,type:"uint"},maxStalenessSeconds:{target:"readPreference",transform({name:e,options:t,values:[o]}){const n=A(e,o);return t.readPreference?g.ReadPreference.fromOptions({readPreference:{...t.readPreference,maxStalenessSeconds:n}}):new g.ReadPreference("secondary",void 0,{maxStalenessSeconds:n})}},minInternalBufferSize:{type:"uint"},minPoolSize:{default:0,type:"uint"},minHeartbeatFrequencyMS:{default:500,type:"uint"},monitorCommands:{default:!1,type:"boolean"},name:{target:"driverInfo",transform:({values:[e],options:t})=>({...t.driverInfo,name:String(e)})},noDelay:{default:!0,type:"boolean"},pkFactory:{default:S.DEFAULT_PK_FACTORY,transform({values:[e]}){if((0,S.isRecord)(e,["createPk"])&&"function"==typeof e.createPk)return e;throw new u.MongoParseError(`Option pkFactory must be an object with a createPk function, got ${e}`)}},promoteBuffers:{type:"boolean"},promoteLongs:{type:"boolean"},promoteValues:{type:"boolean"},useBigInt64:{type:"boolean"},proxyHost:{type:"string"},proxyPassword:{type:"string"},proxyPort:{type:"uint"},proxyUsername:{type:"string"},raw:{default:!1,type:"boolean"},readConcern:{transform({values:[e],options:t}){if(e instanceof p.ReadConcern||(0,S.isRecord)(e,["level"]))return p.ReadConcern.fromOptions({...t.readConcern,...e});throw new u.MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(e)}`)}},readConcernLevel:{target:"readConcern",transform:({values:[e],options:t})=>p.ReadConcern.fromOptions({...t.readConcern,level:e})},readPreference:{default:g.ReadPreference.primary,transform({values:[e],options:t}){if(e instanceof g.ReadPreference)return g.ReadPreference.fromOptions({readPreference:{...t.readPreference,...e},...e});if((0,S.isRecord)(e,["mode"])){const o=g.ReadPreference.fromOptions({readPreference:{...t.readPreference,...e},...e});if(o)return o;throw new u.MongoParseError(`Cannot make read preference from ${JSON.stringify(e)}`)}if("string"==typeof e){const o={hedge:t.readPreference?.hedge,maxStalenessSeconds:t.readPreference?.maxStalenessSeconds};return new g.ReadPreference(e,t.readPreference?.tags,o)}throw new u.MongoParseError(`Unknown ReadPreference value: ${e}`)}},readPreferenceTags:{target:"readPreference",transform({values:e,options:t}){const o=Array.isArray(e[0])?e[0]:e,n=[];for(const e of o){const t=Object.create(null);if("string"==typeof e)for(const[o,n]of _(e))t[o]=n;if((0,S.isRecord)(e))for(const[o,n]of Object.entries(e))t[o]=n;n.push(t)}return g.ReadPreference.fromOptions({readPreference:t.readPreference,readPreferenceTags:n})}},replicaSet:{type:"string"},retryReads:{default:!0,type:"boolean"},retryWrites:{default:!0,type:"boolean"},serializeFunctions:{type:"boolean"},serverMonitoringMode:{default:"auto",transform({values:[e]}){if(!Object.values(f.ServerMonitoringMode).includes(e))throw new u.MongoParseError("serverMonitoringMode must be one of `auto`, `poll`, or `stream`");return e}},serverSelectionTimeoutMS:{default:3e4,type:"uint"},servername:{type:"string"},socketTimeoutMS:{default:0,type:"uint"},srvMaxHosts:{type:"uint",default:0},srvServiceName:{type:"string",default:"mongodb"},ssl:{target:"tls",type:"boolean"},timeoutMS:{type:"uint"},tls:{type:"boolean"},tlsAllowInvalidCertificates:{target:"rejectUnauthorized",transform:({name:e,values:[t]})=>!v(e,t)},tlsAllowInvalidHostnames:{target:"checkServerIdentity",transform:({name:e,values:[t]})=>v(e,t)?()=>{}:void 0},tlsCAFile:{type:"string"},tlsCRLFile:{type:"string"},tlsCertificateKeyFile:{type:"string"},tlsCertificateKeyFilePassword:{target:"passphrase",type:"any"},tlsInsecure:{transform({name:e,options:t,values:[o]}){const n=v(e,o);return n?(t.checkServerIdentity=()=>{},t.rejectUnauthorized=!1):(t.checkServerIdentity=t.tlsAllowInvalidHostnames?()=>{}:void 0,t.rejectUnauthorized=!t.tlsAllowInvalidCertificates),n}},w:{target:"writeConcern",transform:({values:[e],options:t})=>E.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,w:e}})},waitQueueTimeoutMS:{default:0,type:"uint"},writeConcern:{target:"writeConcern",transform({values:[e],options:t}){if((0,S.isRecord)(e)||e instanceof E.WriteConcern)return E.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,...e}});if("majority"===e||"number"==typeof e)return E.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,w:e}});throw new u.MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(e)}`)}},wtimeout:{deprecated:"Please use wtimeoutMS instead",target:"writeConcern",transform({values:[e],options:t}){const o=E.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,wtimeout:A("wtimeout",e)}});if(o)return o;throw new u.MongoParseError("Cannot make WriteConcern from wtimeout")}},wtimeoutMS:{target:"writeConcern",transform({values:[e],options:t}){const o=E.WriteConcern.fromOptions({writeConcern:{...t.writeConcern,wtimeoutMS:A("wtimeoutMS",e)}});if(o)return o;throw new u.MongoParseError("Cannot make WriteConcern from wtimeout")}},zlibCompressionLevel:{default:0,type:"int"},mongodbLogPath:{transform({values:[e]}){if(!("string"==typeof e&&["stderr","stdout"].includes(e)||e&&"object"==typeof e&&"write"in e&&"function"==typeof e.write))throw new u.MongoAPIError("Option 'mongodbLogPath' must be of type 'stderr' | 'stdout' | MongoDBLogWritable");return e}},mongodbLogComponentSeverities:{transform({values:[e]}){if("object"!=typeof e||!e)throw new u.MongoAPIError("Option 'mongodbLogComponentSeverities' must be a non-null object");for(const[t,o]of Object.entries(e)){if("string"!=typeof o||"string"!=typeof t)throw new u.MongoAPIError("User input for option 'mongodbLogComponentSeverities' object cannot include a non-string key or value");if(!Object.values(m.MongoLoggableComponent).some((e=>e===t))&&"default"!==t)throw new u.MongoAPIError(`User input for option 'mongodbLogComponentSeverities' contains invalid key: ${t}`);if(!Object.values(m.SeverityLevel).some((e=>e===o)))throw new u.MongoAPIError(`Option 'mongodbLogComponentSeverities' does not support ${o} as a value for ${t}`)}return e}},mongodbLogMaxDocumentLength:{type:"uint"},connectionType:{type:"any"},srvPoller:{type:"any"},allowPartialTrustChain:{type:"any"},minDHSize:{type:"any"},pskCallback:{type:"any"},secureContext:{type:"any"},enableTrace:{type:"any"},requestCert:{type:"any"},rejectUnauthorized:{type:"any"},checkServerIdentity:{type:"any"},keepAliveInitialDelay:{type:"any"},ALPNProtocols:{type:"any"},SNICallback:{type:"any"},session:{type:"any"},requestOCSP:{type:"any"},localAddress:{type:"any"},localPort:{type:"any"},hints:{type:"any"},lookup:{type:"any"},ca:{type:"any"},cert:{type:"any"},ciphers:{type:"any"},crl:{type:"any"},ecdhCurve:{type:"any"},key:{type:"any"},passphrase:{type:"any"},pfx:{type:"any"},secureProtocol:{type:"any"},index:{type:"any"},__skipPingOnConnect:{type:"boolean"}},t.DEFAULT_OPTIONS=new I(Object.entries(t.OPTIONS).filter((([,e])=>null!=e.default)).map((([e,t])=>[e,t.default])))},53373:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChangeStream=void 0,t.filterOutOptions=E;const n=o(53975),r=o(34842),i=o(40927),s=o(50700),a=o(3137),c=o(36997),l=o(88757),d=o(72361),u=o(26119),h=o(33628),m=o(30306),p={COLLECTION:Symbol("Collection"),DATABASE:Symbol("Database"),CLUSTER:Symbol("Cluster")},g=[r.RESUME_TOKEN_CHANGED,r.END,r.CLOSE],f="ChangeStream is closed",S=new Set(Object.keys({allowDiskUse:"",authdb:"",batchSize:"",bsonRegExp:"",bypassDocumentValidation:"",bypassPinningCheck:"",checkKeys:"",collation:"",comment:"",cursor:"",dbName:"",enableUtf8Validation:"",explain:"",fieldsAsRaw:"",hint:"",ignoreUndefined:"",let:"",maxAwaitTimeMS:"",maxTimeMS:"",omitMaxTimeMS:"",out:"",promoteBuffers:"",promoteLongs:"",promoteValues:"",raw:"",rawData:"",readConcern:"",readPreference:"",serializeFunctions:"",session:"",timeoutContext:"",timeoutMS:"",timeoutMode:"",useBigInt64:"",willRetryWrite:"",writeConcern:""}));function E(e){return Object.fromEntries(Object.entries(e).filter((([e,t])=>!S.has(e))))}class y extends d.TypedEventEmitter{async[Symbol.asyncDispose](){await this.close()}static{this.RESPONSE=r.RESPONSE}static{this.MORE=r.MORE}static{this.INIT=r.INIT}static{this.CLOSE=r.CLOSE}static{this.CHANGE=r.CHANGE}static{this.END=r.END}static{this.ERROR=r.ERROR}static{this.RESUME_TOKEN_CHANGED=r.RESUME_TOKEN_CHANGED}constructor(e,t=[],o={}){let r;if(super(),this.pipeline=t,this.options={...o},delete this.options.writeConcern,e instanceof n.Collection)this.type=p.COLLECTION,r=e.s.db.client.options.serverSelectionTimeoutMS;else if(e instanceof a.Db)this.type=p.DATABASE,r=e.client.options.serverSelectionTimeoutMS;else{if(!(e instanceof l.MongoClient))throw new c.MongoChangeStreamError("Parent provided to ChangeStream constructor must be an instance of Collection, Db, or MongoClient");this.type=p.CLUSTER,r=e.options.serverSelectionTimeoutMS}this.contextOwner=Symbol(),this.parent=e,this.namespace=e.s.namespace,!this.options.readPreference&&e.readPreference&&(this.options.readPreference=e.readPreference),this.cursor=this._createChangeStreamCursor(o),this.isClosed=!1,this.mode=!1,this.on("newListener",(e=>{"change"===e&&this.cursor&&0===this.listenerCount("change")&&this._streamEvents(this.cursor)})),this.on("removeListener",(e=>{"change"===e&&0===this.listenerCount("change")&&this.cursor&&this.cursorStream?.removeAllListeners("data")})),null!=this.options.timeoutMS&&(this.timeoutContext=new h.CSOTTimeoutContext({timeoutMS:this.options.timeoutMS,serverSelectionTimeoutMS:r}))}get resumeToken(){return this.cursor?.resumeToken}async hasNext(){this._setIsIterator(),this.timeoutContext?.refresh();try{for(;;)try{return await this.cursor.hasNext()}catch(e){try{await this._processErrorIteratorMode(e,null!=this.cursor.id)}catch(e){if(e instanceof c.MongoOperationTimeoutError&&null==this.cursor.id)throw e;try{await this.close()}catch(e){(0,m.squashError)(e)}throw e}}}finally{this.timeoutContext?.clear()}}async next(){this._setIsIterator(),this.timeoutContext?.refresh();try{for(;;)try{const e=await this.cursor.next();return this._processChange(e??null)}catch(e){try{await this._processErrorIteratorMode(e,null!=this.cursor.id)}catch(e){if(e instanceof c.MongoOperationTimeoutError&&null==this.cursor.id)throw e;try{await this.close()}catch(e){(0,m.squashError)(e)}throw e}}}finally{this.timeoutContext?.clear()}}async tryNext(){this._setIsIterator(),this.timeoutContext?.refresh();try{for(;;)try{const e=await this.cursor.tryNext();return e?this._processChange(e):null}catch(e){try{await this._processErrorIteratorMode(e,null!=this.cursor.id)}catch(e){if(e instanceof c.MongoOperationTimeoutError&&null==this.cursor.id)throw e;try{await this.close()}catch(e){(0,m.squashError)(e)}throw e}}}finally{this.timeoutContext?.clear()}}async*[Symbol.asyncIterator](){if(!this.closed)try{for(;;)yield await this.next()}finally{try{await this.close()}catch(e){(0,m.squashError)(e)}}}get closed(){return this.isClosed||this.cursor.closed}async close(){this.timeoutContext?.clear(),this.timeoutContext=void 0,this.isClosed=!0;const e=this.cursor;try{await e.close()}finally{this._endStream()}}stream(){if(this.closed)throw new c.MongoChangeStreamError(f);return this.cursor.stream()}_setIsEmitter(){if("iterator"===this.mode)throw new c.MongoAPIError("ChangeStream cannot be used as an EventEmitter after being used as an iterator");this.mode="emitter"}_setIsIterator(){if("emitter"===this.mode)throw new c.MongoAPIError("ChangeStream cannot be used as an iterator after being used as an EventEmitter");this.mode="iterator"}_createChangeStreamCursor(e){const t=E(e);this.type===p.CLUSTER&&(t.allChangesForCluster=!0);const o=[{$changeStream:t},...this.pipeline],n=this.type===p.CLUSTER?this.parent:this.type===p.DATABASE||this.type===p.COLLECTION?this.parent.client:null;if(null==n)throw new c.MongoRuntimeError(`Changestream type should only be one of cluster, database, collection. Found ${this.type.toString()}`);const r=new s.ChangeStreamCursor(n,this.namespace,o,{...e,timeoutContext:this.timeoutContext?new i.CursorTimeoutContext(this.timeoutContext,this.contextOwner):void 0});for(const e of g)r.on(e,(t=>this.emit(e,t)));return this.listenerCount(y.CHANGE)>0&&this._streamEvents(r),r}_closeEmitterModeWithError(e){this.emit(y.ERROR,e),this.close().then(void 0,m.squashError)}_streamEvents(e){this._setIsEmitter();const t=this.cursorStream??e.stream();this.cursorStream=t,t.on("data",(e=>{try{const t=this._processChange(e);this.emit(y.CHANGE,t)}catch(e){this.emit(y.ERROR,e)}this.timeoutContext?.refresh()})),t.on("error",(e=>this._processErrorStreamMode(e,null!=this.cursor.id)))}_endStream(){this.cursorStream?.removeAllListeners("data"),this.cursorStream?.removeAllListeners("close"),this.cursorStream?.removeAllListeners("end"),this.cursorStream?.destroy(),this.cursorStream=void 0}_processChange(e){if(this.isClosed)throw new c.MongoAPIError(f);if(null==e)throw new c.MongoRuntimeError(f);if(e&&!e._id)throw new c.MongoChangeStreamError("A change stream document has been received that lacks a resume token (_id).");return this.cursor.cacheResumeToken(e._id),this.options.startAtOperationTime=void 0,e}_processErrorStreamMode(e,t){this.isClosed||(t&&((0,c.isResumableError)(e,this.cursor.maxWireVersion)||e instanceof c.MongoOperationTimeoutError)?(this._endStream(),this.cursor.close().then((()=>this._resume(e)),(t=>((0,m.squashError)(t),this._resume(e)))).then((()=>{e instanceof c.MongoOperationTimeoutError&&this.emit(y.ERROR,e)}),(()=>this._closeEmitterModeWithError(e)))):this._closeEmitterModeWithError(e))}async _processErrorIteratorMode(e,t){if(this.isClosed)throw new c.MongoAPIError(f);if(!t||!((0,c.isResumableError)(e,this.cursor.maxWireVersion)||e instanceof c.MongoOperationTimeoutError)){try{await this.close()}catch(e){(0,m.squashError)(e)}throw e}try{await this.cursor.close()}catch(e){(0,m.squashError)(e)}if(await this._resume(e),e instanceof c.MongoOperationTimeoutError)throw e}async _resume(e){this.timeoutContext?.refresh();const t=(0,m.getTopology)(this.parent);try{await t.selectServer(this.cursor.readPreference,{operationName:"reconnect topology in change stream",timeoutContext:this.timeoutContext,deprioritizedServers:new u.DeprioritizedServers}),this.cursor=this._createChangeStreamCursor(this.cursor.resumeOptions)}catch{throw await this.close(),e}}}t.ChangeStream=y},53482:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SetProfilingLevelOperation=t.ProfilingLevel=void 0;const n=o(72216),r=o(36997),i=o(30306),s=o(41539),a=new Set(["off","slow_only","all"]);t.ProfilingLevel=Object.freeze({off:"off",slowOnly:"slow_only",all:"all"});class c extends s.CommandOperation{constructor(e,o,r){switch(super(e,r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=r,o){case t.ProfilingLevel.off:this.profile=0;break;case t.ProfilingLevel.slowOnly:this.profile=1;break;case t.ProfilingLevel.all:this.profile=2;break;default:this.profile=0}this.level=o}get commandName(){return"profile"}buildCommandDocument(e){const o=this.level;if(!a.has(o))throw new r.MongoInvalidArgumentError(`Profiling level must be one of "${(0,i.enumToString)(t.ProfilingLevel)}"`);return{profile:this.profile}}handleOk(e){return this.level}}t.SetProfilingLevelOperation=c},53975:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Collection=void 0;const n=o(77953),r=o(80529),i=o(32328),s=o(53373),a=o(13237),c=o(12668),l=o(10176),d=o(94289),u=o(36997),h=o(85673),m=o(27827),p=o(29976),g=o(23942),f=o(39131),S=o(95174),E=o(15002),y=o(11337),b=o(75878),O=o(92294),C=o(86675),M=o(51499),T=o(82521),w=o(86552),v=o(74891),R=o(30306),A=o(71259);t.Collection=class{constructor(e,t,o){this.db=e,this.s={db:e,options:o,namespace:new R.MongoDBCollectionNamespace(e.databaseName,t),pkFactory:e.options?.pkFactory??R.DEFAULT_PK_FACTORY,readPreference:v.ReadPreference.fromOptions(o),bsonOptions:(0,n.resolveBSONOptions)(o,e),readConcern:w.ReadConcern.fromOptions(o),writeConcern:A.WriteConcern.fromOptions(o)},this.client=e.client}get dbName(){return this.s.namespace.db}get collectionName(){return this.s.namespace.collection}get namespace(){return this.fullNamespace.toString()}get fullNamespace(){return this.s.namespace}get readConcern(){return null==this.s.readConcern?this.db.readConcern:this.s.readConcern}get readPreference(){return null==this.s.readPreference?this.db.readPreference:this.s.readPreference}get bsonOptions(){return this.s.bsonOptions}get writeConcern(){return null==this.s.writeConcern?this.db.writeConcern:this.s.writeConcern}get hint(){return this.s.collectionHint}set hint(e){this.s.collectionHint=(0,R.normalizeHintField)(e)}get timeoutMS(){return this.s.options.timeoutMS}async insertOne(e,t){return await(0,f.executeOperation)(this.client,new y.InsertOneOperation(this,e,(0,R.resolveOptions)(this,t)))}async insertMany(e,t){if(!Array.isArray(e))throw new u.MongoInvalidArgumentError('Argument "docs" must be an array of documents');t=(0,R.resolveOptions)(this,t??{});const o=0!==A.WriteConcern.fromOptions(t)?.w;try{const n=await this.bulkWrite(e.map((e=>({insertOne:{document:e}}))),t);return{acknowledged:o,insertedCount:n.insertedCount,insertedIds:n.insertedIds}}catch(e){if(e&&"Operation must be an object with an operation key"===e.message)throw new u.MongoInvalidArgumentError("Collection.insertMany() cannot be called with an array that has null/undefined values");throw e}}async bulkWrite(e,t){if(!Array.isArray(e))throw new u.MongoInvalidArgumentError('Argument "operations" must be an array of documents');t=(0,R.resolveOptions)(this,t??{}),null!=this.client.topology||await(0,f.autoConnect)(this.client);const o=!1===t.ordered?this.initializeUnorderedBulkOp(t):this.initializeOrderedBulkOp(t);for(const t of e)o.raw(t);return await o.execute({...t})}async updateOne(e,t,o){return await(0,f.executeOperation)(this.client,new T.UpdateOneOperation(this.s.namespace,e,t,(0,R.resolveOptions)(this,o)))}async replaceOne(e,t,o){return await(0,f.executeOperation)(this.client,new T.ReplaceOneOperation(this.s.namespace,e,t,(0,R.resolveOptions)(this,o)))}async updateMany(e,t,o){return await(0,f.executeOperation)(this.client,new T.UpdateManyOperation(this.s.namespace,e,t,(0,R.resolveOptions)(this,o)))}async deleteOne(e={},t={}){return await(0,f.executeOperation)(this.client,new m.DeleteOneOperation(this.s.namespace,e,(0,R.resolveOptions)(this,t)))}async deleteMany(e={},t={}){return await(0,f.executeOperation)(this.client,new m.DeleteManyOperation(this.s.namespace,e,(0,R.resolveOptions)(this,t)))}async rename(e,t){return await(0,f.executeOperation)(this.client,new b.RenameOperation(this,e,(0,R.resolveOptions)(void 0,{...t,readPreference:v.ReadPreference.PRIMARY})))}async drop(e){return await this.db.dropCollection(this.collectionName,e)}async findOne(e={},t={}){const{...o}=t;o.singleBatch=!0;const n=this.find(e,o).limit(1),r=await n.next();return await n.close(),r}find(e={},t={}){return new c.FindCursor(this.client,this.s.namespace,e,(0,R.resolveOptions)(this,t))}async options(e){e=(0,R.resolveOptions)(this,e);const[t]=await this.db.listCollections({name:this.collectionName},{...e,nameOnly:!1}).toArray();if(null==t||null==t.options)throw new u.MongoAPIError(`collection ${this.namespace} not found`);return t.options}async isCapped(e){const{capped:t}=await this.options(e);return Boolean(t)}async createIndex(e,t){return(await(0,f.executeOperation)(this.client,E.CreateIndexesOperation.fromIndexSpecification(this,this.collectionName,e,(0,R.resolveOptions)(this,t))))[0]}async createIndexes(e,t){return await(0,f.executeOperation)(this.client,E.CreateIndexesOperation.fromIndexDescriptionArray(this,this.collectionName,e,(0,R.resolveOptions)(this,{...t,maxTimeMS:void 0})))}async dropIndex(e,t){return await(0,f.executeOperation)(this.client,new E.DropIndexOperation(this,e,{...(0,R.resolveOptions)(this,t),readPreference:v.ReadPreference.primary}))}async dropIndexes(e){try{return await(0,f.executeOperation)(this.client,new E.DropIndexOperation(this,"*",(0,R.resolveOptions)(this,e))),!0}catch(e){if(e instanceof u.MongoOperationTimeoutError)throw e;return!1}}listIndexes(e){return new l.ListIndexesCursor(this,(0,R.resolveOptions)(this,e))}async indexExists(e,t){const o=Array.isArray(e)?e:[e],n=new Set(await this.listIndexes(t).map((({name:e})=>e)).toArray());return o.every((e=>n.has(e)))}async indexInformation(e){return await this.indexes({...e,full:e?.full??!1})}async estimatedDocumentCount(e){return await(0,f.executeOperation)(this.client,new g.EstimatedDocumentCountOperation(this,(0,R.resolveOptions)(this,e)))}async countDocuments(e={},t={}){const o=[];o.push({$match:e}),"number"==typeof t.skip&&o.push({$skip:t.skip}),"number"==typeof t.limit&&o.push({$limit:t.limit}),o.push({$group:{_id:1,n:{$sum:1}}});const n=this.aggregate(o,t),r=await n.next();return await n.close(),r?.n??0}async distinct(e,t={},o={}){return await(0,f.executeOperation)(this.client,new p.DistinctOperation(this,e,t,(0,R.resolveOptions)(this,o)))}async indexes(e){const t=await this.listIndexes(e).toArray();return e?.full??1?t:Object.fromEntries(t.map((({name:e,key:t})=>[e,Object.entries(t)])))}async findOneAndDelete(e,t){return await(0,f.executeOperation)(this.client,new S.FindOneAndDeleteOperation(this,e,(0,R.resolveOptions)(this,t)))}async findOneAndReplace(e,t,o){return await(0,f.executeOperation)(this.client,new S.FindOneAndReplaceOperation(this,e,t,(0,R.resolveOptions)(this,o)))}async findOneAndUpdate(e,t,o){return await(0,f.executeOperation)(this.client,new S.FindOneAndUpdateOperation(this,e,t,(0,R.resolveOptions)(this,o)))}aggregate(e=[],t){if(!Array.isArray(e))throw new u.MongoInvalidArgumentError('Argument "pipeline" must be an array of aggregation stages');return new a.AggregationCursor(this.client,this.s.namespace,e,(0,R.resolveOptions)(this,t))}watch(e=[],t={}){return Array.isArray(e)||(t=e,e=[]),new s.ChangeStream(this,e,(0,R.resolveOptions)(this,t))}initializeUnorderedBulkOp(e){return new i.UnorderedBulkOperation(this,(0,R.resolveOptions)(this,e))}initializeOrderedBulkOp(e){return new r.OrderedBulkOperation(this,(0,R.resolveOptions)(this,e))}async count(e={},t={}){return await(0,f.executeOperation)(this.client,new h.CountOperation(this.fullNamespace,e,(0,R.resolveOptions)(this,t)))}listSearchIndexes(e,t){t="object"==typeof e?e:null==t?{}:t;const o=null==e||"object"==typeof e?null:e;return new d.ListSearchIndexesCursor(this,o,t)}async createSearchIndex(e){const[t]=await this.createSearchIndexes([e]);return t}async createSearchIndexes(e){return await(0,f.executeOperation)(this.client,new O.CreateSearchIndexesOperation(this,e))}async dropSearchIndex(e){return await(0,f.executeOperation)(this.client,new C.DropSearchIndexOperation(this,e))}async updateSearchIndex(e,t){return await(0,f.executeOperation)(this.client,new M.UpdateSearchIndexOperation(this,e,t))}}},57319:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceProviderCore=void 0;const n=o(92762),r=o(41330);t.ServiceProviderCore=class{constructor(e){if(void 0===e)throw new n.MongoshInternalError("BSON Library is undefined.");(0,r.makePrintableBson)(e),this.bsonLibrary=e}}},57797:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mapCliToDriver=void 0,t.generateConnectionInfoFromCliArgs=function(e){const t=(0,n.generateUri)(e);return(0,r.mapCliToDriver)(e,{connectionString:t,driverOptions:{}})};const n=o(83811),r=o(10187);Object.defineProperty(t,"mapCliToDriver",{enumerable:!0,get:function(){return r.mapCliToDriver}})},58514:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onData=function(e,{timeoutContext:t,signal:o}){o?.throwIfAborted();const r=new n.List,i=new n.List;let s=null,a=!1;const c={next(){const e=r.shift();if(null!=e)return Promise.resolve({value:e,done:!1});if(null!=s){const e=Promise.reject(s);return s=null,e}if(a)return m();const{promise:t,resolve:o,reject:c}=(0,n.promiseWithResolvers)();return i.push({resolve:o,reject:c}),t},return:()=>m(),throw:e=>(h(e),Promise.resolve({value:void 0,done:!0})),[Symbol.asyncIterator](){return this},async[Symbol.asyncDispose](){await m()}};e.on("data",u),e.on("error",h);const l=(0,n.addAbortListener)(o,(function(){h(this.reason)})),d=t?.timeoutForSocketRead;return d?.throwIfExpired(),d?.then(void 0,h),c;function u(e){const t=i.shift();null!=t?t.resolve({value:e,done:!1}):r.push(e)}function h(e){const t=i.shift();null!=t?t.reject(e):s=e,m()}function m(){e.off("data",u),e.off("error",h),l?.[n.kDispose](),a=!0,d?.clear();const t={value:void 0,done:a};for(const e of i)e.resolve(t);return Promise.resolve(t)}};const n=o(30306)},59937:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongocryptdManager=void 0;const n=o(36997);class r{static{this.DEFAULT_MONGOCRYPTD_URI="mongodb://localhost:27020"}constructor(e={}){this.spawnPath="",this.spawnArgs=[],this.uri="string"==typeof e.mongocryptdURI&&e.mongocryptdURI.length>0?e.mongocryptdURI:r.DEFAULT_MONGOCRYPTD_URI,this.bypassSpawn=!!e.mongocryptdBypassSpawn,Object.hasOwn(e,"mongocryptdSpawnPath")&&e.mongocryptdSpawnPath&&(this.spawnPath=e.mongocryptdSpawnPath),Object.hasOwn(e,"mongocryptdSpawnArgs")&&Array.isArray(e.mongocryptdSpawnArgs)&&(this.spawnArgs=this.spawnArgs.concat(e.mongocryptdSpawnArgs)),this.spawnArgs.filter((e=>"string"==typeof e)).every((e=>e.indexOf("--idleShutdownTimeoutSecs")<0))&&this.spawnArgs.push("--idleShutdownTimeoutSecs","60")}async spawn(){const e=this.spawnPath||"mongocryptd",{spawn:t}=o(16154);this._child=t(e,this.spawnArgs,{stdio:"ignore",detached:!0}),this._child.on("error",(()=>{})),this._child.unref()}async withRespawn(e){try{return await e()}catch(e){if(!(e instanceof n.MongoNetworkTimeoutError)||this.bypassSpawn)throw e}return await this.spawn(),await e()}}t.MongocryptdManager=r},60239:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TokenCache=void 0;const n=o(36997);class r extends n.MongoDriverError{}t.TokenCache=class{get hasAccessToken(){return!!this.accessToken}get hasRefreshToken(){return!!this.refreshToken}get hasIdpInfo(){return!!this.idpInfo}getAccessToken(){if(!this.accessToken)throw new r("Attempted to get an access token when none exists.");return this.accessToken}getRefreshToken(){if(!this.refreshToken)throw new r("Attempted to get a refresh token when none exists.");return this.refreshToken}getIdpInfo(){if(!this.idpInfo)throw new r("Attempted to get IDP information when none exists.");return this.idpInfo}put(e,t){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expiresInSeconds=e.expiresInSeconds,t&&(this.idpInfo=t)}removeAccessToken(){this.accessToken=void 0}removeRefreshToken(){this.refreshToken=void 0}}},60449:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SENSITIVE_COMMANDS=t.CommandFailedEvent=t.CommandSucceededEvent=t.CommandStartedEvent=void 0;const n=o(34842),r=o(30306),i=o(87535);t.CommandStartedEvent=class{constructor(e,o,r){this.name=n.COMMAND_STARTED;const i=h(o),s=a(i),{address:c,connectionId:d,serviceId:u}=m(e);t.SENSITIVE_COMMANDS.has(s)&&(this.commandObj={},this.commandObj[s]=!0),this.address=c,this.connectionId=d,this.serviceId=u,this.requestId=o.requestId,this.databaseName=o.databaseName,this.commandName=s,this.command=l(s,i,i),this.serverConnectionId=r}get hasServiceId(){return!!this.serviceId}},t.CommandSucceededEvent=class{constructor(e,t,o,i,s){this.name=n.COMMAND_SUCCEEDED;const c=h(t),d=a(c),{address:u,connectionId:p,serviceId:g}=m(e);this.address=u,this.connectionId=p,this.serviceId=g,this.requestId=t.requestId,this.commandName=d,this.duration=(0,r.calculateDurationInMs)(i),this.reply=l(d,c,function(e){return e&&e.result?e.result:e}(o)),this.serverConnectionId=s,this.databaseName=t.databaseName}get hasServiceId(){return!!this.serviceId}},t.CommandFailedEvent=class{constructor(e,t,o,i,s){this.name=n.COMMAND_FAILED;const c=h(t),d=a(c),{address:u,connectionId:p,serviceId:g}=m(e);this.address=u,this.connectionId=p,this.serviceId=g,this.requestId=t.requestId,this.commandName=d,this.duration=(0,r.calculateDurationInMs)(i),this.failure=l(d,c,o),this.serverConnectionId=s,this.databaseName=t.databaseName}get hasServiceId(){return!!this.serviceId}},t.SENSITIVE_COMMANDS=new Set(["authenticate","saslStart","saslContinue","getnonce","createUser","updateUser","copydbgetnonce","copydbsaslstart","copydb"]);const s=new Set(["hello",n.LEGACY_HELLO_COMMAND,n.LEGACY_HELLO_COMMAND_CAMEL_CASE]),a=e=>Object.keys(e)[0],c=e=>e.ns.split(".")[1],l=(e,o,n)=>t.SENSITIVE_COMMANDS.has(e)||s.has(e)&&o.speculativeAuthenticate?{}:n,d={$query:"filter",$orderby:"sort",$hint:"hint",$comment:"comment",$maxScan:"maxScan",$max:"max",$min:"min",$returnKey:"returnKey",$showDiskLoc:"showRecordId",$maxTimeMS:"maxTimeMS",$snapshot:"snapshot"},u={numberToSkip:"skip",numberToReturn:"batchSize",returnFieldSelector:"projection"};function h(e){if(e instanceof i.OpMsgRequest){const t={...e.command};return t.ops instanceof i.DocumentSequence&&(t.ops=t.ops.documents),t.nsInfo instanceof i.DocumentSequence&&(t.nsInfo=t.nsInfo.documents),t}if(e.query?.$query){let t;return"admin.$cmd"===e.ns?t=Object.assign({},e.query.$query):(t={find:c(e)},Object.keys(d).forEach((o=>{null!=e.query[o]&&(t[d[o]]={...e.query[o]})}))),Object.keys(u).forEach((o=>{const n=o;null!=e[n]&&(t[u[n]]=e[n])})),t}let t={};const o={...e};return e.query&&(t={...e.query},o.query=t),e.query?t:o}function m(e){let t;return"id"in e&&(t=e.id),{address:e.address,serviceId:e.serviceId,connectionId:t}}},60866:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoLogger=t.MongoLoggableComponent=t.SEVERITY_LEVEL_MAP=t.DEFAULT_MAX_DOCUMENT_LENGTH=t.SeverityLevel=void 0,t.parseSeverityFromString=l,t.createStdioLogger=d,t.stringifyWithMaxLen=m,t.defaultLogTransform=y;const n=o(15088),r=o(13390),i=o(77953),s=o(34842),a=o(30306);t.SeverityLevel=Object.freeze({EMERGENCY:"emergency",ALERT:"alert",CRITICAL:"critical",ERROR:"error",WARNING:"warn",NOTICE:"notice",INFORMATIONAL:"info",DEBUG:"debug",TRACE:"trace",OFF:"off"}),t.DEFAULT_MAX_DOCUMENT_LENGTH=1e3;class c extends Map{constructor(e){const t=[];for(const[o,n]of e)t.push([n,o]);t.push(...e),super(t)}getNumericSeverityLevel(e){return this.get(e)}getSeverityLevelName(e){return this.get(e)}}function l(e){const o=Object.values(t.SeverityLevel),n=e?.toLowerCase();return null!=n&&o.includes(n)?n:null}function d(e){return{write:t=>new Promise(((o,n)=>{const i=(0,r.inspect)(t,{compact:!0,breakLength:1/0});e.write(`${i}\n`,"utf-8",(e=>{if(e)return n(e);o(!0)}))}))}}function u(e,t,o){return l(e)??l(t)??o}function h(e,o){const n=t.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(e),r=t.SEVERITY_LEVEL_MAP.getNumericSeverityLevel(o);return n<r?-1:n>r?1:0}function m(e,t,o={}){let n="",r=0;const s=function(e,o){if(!(r>=t)){if(""===e)return r+=1,o;if(r+=e.length+4,null==o)return o;switch(typeof o){case"string":r+=o.length+2;break;case"number":case"bigint":r+=String(o).length;break;case"boolean":r+=o?4:5;break;case"object":if((0,a.isUint8Array)(o))r+=22+o.byteLength+.33*o.byteLength+18|0;else if("_bsontype"in o){const e=o;switch(e._bsontype){case"Int32":r+=String(e.value).length;break;case"Double":r+=(0|e.value)===e.value?String(e.value).length+2:String(e.value).length;break;case"Long":r+=e.toString().length;break;case"ObjectId":r+=35;break;case"MaxKey":case"MinKey":r+=13;break;case"Binary":r+=22+o.position+.33*o.position+18|0;break;case"Timestamp":r+=19+String(e.t).length+5+String(e.i).length+2;break;case"Code":null==e.scope?r+=e.code.length+10+2:r+=e.code.length+10+11;break;case"BSONRegExp":r+=34+e.pattern.length+13+e.options.length+3}}}return o}};if("string"==typeof e)n=e;else if("function"==typeof e)n=e.name;else try{n=0!==t?i.EJSON.stringify(e,s,0,o):i.EJSON.stringify(e,o)}catch(e){n=`Extended JSON serialization failed with: ${e.message}`}return 0!==t&&n.length>t&&n.charCodeAt(t-1)!==n.codePointAt(t-1)&&0==--t?"":0!==t&&n.length>t?`${n.slice(0,t)}...`:n}function p(e,o,n=t.DEFAULT_MAX_DOCUMENT_LENGTH){const{selector:r,operation:i,topologyDescription:s,message:a}=o;return e.selector=m(r,n),e.operation=i,e.topologyDescription=m(s,n),e.message=a,e}function g(e,t){e.commandName=t.commandName,e.requestId=t.requestId,e.driverConnectionId=t.connectionId;const{host:o,port:n}=a.HostAddress.fromString(t.address).toHostPort();return e.serverHost=o,e.serverPort=n,t?.serviceId&&(e.serviceId=t.serviceId.toHexString()),e.databaseName=t.databaseName,e.serverConnectionId=t.serverConnectionId,e}function f(e,t){const{host:o,port:n}=a.HostAddress.fromString(t.address).toHostPort();return e.serverHost=o,e.serverPort=n,e}function S(e,t){return e.topologyId=t.topologyId,e}function E(e,t){const{awaited:o,connectionId:n}=t;e.awaited=o,e.driverConnectionId=t.connectionId;const{host:r,port:i}=a.HostAddress.fromString(n).toHostPort();return e.serverHost=r,e.serverPort=i,e}function y(e,o=t.DEFAULT_MAX_DOCUMENT_LENGTH){let n=Object.create(null);switch(e.name){case s.SERVER_SELECTION_STARTED:return n=p(n,e,o),n;case s.SERVER_SELECTION_FAILED:return n=p(n,e,o),n.failure=e.failure?.message,n;case s.SERVER_SELECTION_SUCCEEDED:return n=p(n,e,o),n.serverHost=e.serverHost,n.serverPort=e.serverPort,n;case s.WAITING_FOR_SUITABLE_SERVER:return n=p(n,e,o),n.remainingTimeMS=e.remainingTimeMS,n;case s.COMMAND_STARTED:return n=g(n,e),n.message="Command started",n.command=m(e.command,o,{relaxed:!0}),n.databaseName=e.databaseName,n;case s.COMMAND_SUCCEEDED:return n=g(n,e),n.message="Command succeeded",n.durationMS=e.duration,n.reply=m(e.reply,o,{relaxed:!0}),n;case s.COMMAND_FAILED:return n=g(n,e),n.message="Command failed",n.durationMS=e.duration,n.failure=e.failure?.message??"(redacted)",n;case s.CONNECTION_POOL_CREATED:if(n=f(n,e),n.message="Connection pool created",e.options){const{maxIdleTimeMS:t,minPoolSize:o,maxPoolSize:r,maxConnecting:i,waitQueueTimeoutMS:s}=e.options;n={...n,maxIdleTimeMS:t,minPoolSize:o,maxPoolSize:r,maxConnecting:i,waitQueueTimeoutMS:s}}return n;case s.CONNECTION_POOL_READY:return n=f(n,e),n.message="Connection pool ready",n;case s.CONNECTION_POOL_CLEARED:return n=f(n,e),n.message="Connection pool cleared","ObjectId"===e.serviceId?._bsontype&&(n.serviceId=e.serviceId?.toHexString()),n;case s.CONNECTION_POOL_CLOSED:return n=f(n,e),n.message="Connection pool closed",n;case s.CONNECTION_CREATED:return n=f(n,e),n.message="Connection created",n.driverConnectionId=e.connectionId,n;case s.CONNECTION_READY:return n=f(n,e),n.message="Connection ready",n.driverConnectionId=e.connectionId,n.durationMS=e.durationMS,n;case s.CONNECTION_CLOSED:switch(n=f(n,e),n.message="Connection closed",n.driverConnectionId=e.connectionId,e.reason){case"stale":n.reason="Connection became stale because the pool was cleared";break;case"idle":n.reason="Connection has been available but unused for longer than the configured max idle time";break;case"error":n.reason="An error occurred while using the connection",e.error&&(n.error=e.error);break;case"poolClosed":n.reason="Connection pool was closed";break;default:n.reason=`Unknown close reason: ${e.reason}`}return n;case s.CONNECTION_CHECK_OUT_STARTED:return n=f(n,e),n.message="Connection checkout started",n;case s.CONNECTION_CHECK_OUT_FAILED:switch(n=f(n,e),n.message="Connection checkout failed",e.reason){case"poolClosed":n.reason="Connection pool was closed";break;case"timeout":n.reason="Wait queue timeout elapsed without a connection becoming available";break;case"connectionError":n.reason="An error occurred while trying to establish a new connection",e.error&&(n.error=e.error);break;default:n.reason=`Unknown close reason: ${e.reason}`}return n.durationMS=e.durationMS,n;case s.CONNECTION_CHECKED_OUT:return n=f(n,e),n.message="Connection checked out",n.driverConnectionId=e.connectionId,n.durationMS=e.durationMS,n;case s.CONNECTION_CHECKED_IN:return n=f(n,e),n.message="Connection checked in",n.driverConnectionId=e.connectionId,n;case s.SERVER_OPENING:return n=S(n,e),n=f(n,e),n.message="Starting server monitoring",n;case s.SERVER_CLOSED:return n=S(n,e),n=f(n,e),n.message="Stopped server monitoring",n;case s.SERVER_HEARTBEAT_STARTED:return n=S(n,e),n=E(n,e),n.message="Server heartbeat started",n;case s.SERVER_HEARTBEAT_SUCCEEDED:return n=S(n,e),n=E(n,e),n.message="Server heartbeat succeeded",n.durationMS=e.duration,n.serverConnectionId=e.serverConnectionId,n.reply=m(e.reply,o,{relaxed:!0}),n;case s.SERVER_HEARTBEAT_FAILED:return n=S(n,e),n=E(n,e),n.message="Server heartbeat failed",n.durationMS=e.duration,n.failure=e.failure?.message,n;case s.TOPOLOGY_OPENING:return n=S(n,e),n.message="Starting topology monitoring",n;case s.TOPOLOGY_CLOSED:return n=S(n,e),n.message="Stopped topology monitoring",n;case s.TOPOLOGY_DESCRIPTION_CHANGED:return n=S(n,e),n.message="Topology description changed",n.previousDescription=n.reply=m(e.previousDescription,o),n.newDescription=n.reply=m(e.newDescription,o),n;default:for(const[t,o]of Object.entries(e))null!=o&&(n[t]=o)}return n}t.SEVERITY_LEVEL_MAP=new c([[t.SeverityLevel.OFF,-1/0],[t.SeverityLevel.EMERGENCY,0],[t.SeverityLevel.ALERT,1],[t.SeverityLevel.CRITICAL,2],[t.SeverityLevel.ERROR,3],[t.SeverityLevel.WARNING,4],[t.SeverityLevel.NOTICE,5],[t.SeverityLevel.INFORMATIONAL,6],[t.SeverityLevel.DEBUG,7],[t.SeverityLevel.TRACE,8]]),t.MongoLoggableComponent=Object.freeze({COMMAND:"command",TOPOLOGY:"topology",SERVER_SELECTION:"serverSelection",CONNECTION:"connection",CLIENT:"client"}),t.MongoLogger=class{constructor(e){this.pendingLog=null,this.error=this.log.bind(this,"error"),this.warn=this.log.bind(this,"warn"),this.info=this.log.bind(this,"info"),this.debug=this.log.bind(this,"debug"),this.trace=this.log.bind(this,"trace"),this.componentSeverities=e.componentSeverities,this.maxDocumentLength=e.maxDocumentLength,this.logDestination=e.logDestination,this.logDestinationIsStdErr=e.logDestinationIsStdErr,this.severities=this.createLoggingSeverities()}createLoggingSeverities(){const e=Object();for(const o of Object.values(t.MongoLoggableComponent)){e[o]={};for(const n of Object.values(t.SeverityLevel))e[o][n]=h(n,this.componentSeverities[o])<=0}return e}turnOffSeverities(){for(const e of Object.values(t.MongoLoggableComponent)){this.componentSeverities[e]=t.SeverityLevel.OFF;for(const o of Object.values(t.SeverityLevel))this.severities[e][o]=!1}}logWriteFailureHandler(e){if(this.logDestinationIsStdErr)return this.turnOffSeverities(),void this.clearPendingLog();this.logDestination=d(n.stderr),this.logDestinationIsStdErr=!0,this.clearPendingLog(),this.error(t.MongoLoggableComponent.CLIENT,{toLog:function(){return{message:"User input for mongodbLogPath is now invalid. Logging is halted.",error:e.message}}}),this.turnOffSeverities(),this.clearPendingLog()}clearPendingLog(){this.pendingLog=null}willLog(e,o){return o!==t.SeverityLevel.OFF&&this.severities[e][o]}log(e,t,o){if(!this.willLog(t,e))return;let n={t:new Date,c:t,s:e};if("string"==typeof o?n.message=o:"object"==typeof o&&(n=function(e){const t=e;return void 0!==t.toLog&&"function"==typeof t.toLog}(o)?{...n,...o.toLog()}:{...n,...y(o,this.maxDocumentLength)}),(0,a.isPromiseLike)(this.pendingLog))this.pendingLog=this.pendingLog.then((()=>this.logDestination.write(n))).then(this.clearPendingLog.bind(this),this.logWriteFailureHandler.bind(this));else try{const e=this.logDestination.write(n);(0,a.isPromiseLike)(e)&&(this.pendingLog=e.then(this.clearPendingLog.bind(this),this.logWriteFailureHandler.bind(this)))}catch(e){this.logWriteFailureHandler(e)}}static resolveOptions(e,o){const r=function({MONGODB_LOG_PATH:e},{mongodbLogPath:t}){return"string"==typeof t&&/^stderr$/i.test(t)?{mongodbLogPath:d(n.stderr),mongodbLogPathIsStdErr:!0}:"string"==typeof t&&/^stdout$/i.test(t)?{mongodbLogPath:d(n.stdout),mongodbLogPathIsStdErr:!1}:"object"==typeof t&&"function"==typeof t?.write?{mongodbLogPath:t,mongodbLogPathIsStdErr:!1}:e&&/^stderr$/i.test(e)?{mongodbLogPath:d(n.stderr),mongodbLogPathIsStdErr:!0}:e&&/^stdout$/i.test(e)?{mongodbLogPath:d(n.stdout),mongodbLogPathIsStdErr:!1}:{mongodbLogPath:d(n.stderr),mongodbLogPathIsStdErr:!0}}(e,o),i={...e,...o,mongodbLogPath:r.mongodbLogPath,mongodbLogPathIsStdErr:r.mongodbLogPathIsStdErr},s=u(i.mongodbLogComponentSeverities?.default,i.MONGODB_LOG_ALL,t.SeverityLevel.OFF);return{componentSeverities:{command:u(i.mongodbLogComponentSeverities?.command,i.MONGODB_LOG_COMMAND,s),topology:u(i.mongodbLogComponentSeverities?.topology,i.MONGODB_LOG_TOPOLOGY,s),serverSelection:u(i.mongodbLogComponentSeverities?.serverSelection,i.MONGODB_LOG_SERVER_SELECTION,s),connection:u(i.mongodbLogComponentSeverities?.connection,i.MONGODB_LOG_CONNECTION,s),client:u(i.mongodbLogComponentSeverities?.client,i.MONGODB_LOG_CLIENT,s),default:s},maxDocumentLength:i.mongodbLogMaxDocumentLength??(0,a.parseUnsignedInteger)(i.MONGODB_LOG_MAX_DOCUMENT_LENGTH)??1e3,logDestination:i.mongodbLogPath,logDestinationIsStdErr:i.mongodbLogPathIsStdErr}}}},60889:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OP_MSG=t.OP_COMPRESSED=t.OP_DELETE=t.OP_QUERY=t.OP_INSERT=t.OP_UPDATE=t.OP_REPLY=t.MIN_SUPPORTED_RAW_DATA_SERVER_VERSION=t.MIN_SUPPORTED_RAW_DATA_WIRE_VERSION=t.MIN_SUPPORTED_QE_SERVER_VERSION=t.MIN_SUPPORTED_QE_WIRE_VERSION=t.MAX_SUPPORTED_WIRE_VERSION=t.MIN_SUPPORTED_WIRE_VERSION=t.MIN_SUPPORTED_SNAPSHOT_READS_SERVER_VERSION=t.MIN_SUPPORTED_SNAPSHOT_READS_WIRE_VERSION=t.MAX_SUPPORTED_SERVER_VERSION=t.MIN_SUPPORTED_SERVER_VERSION=void 0,t.MIN_SUPPORTED_SERVER_VERSION="4.2",t.MAX_SUPPORTED_SERVER_VERSION="8.2",t.MIN_SUPPORTED_SNAPSHOT_READS_WIRE_VERSION=13,t.MIN_SUPPORTED_SNAPSHOT_READS_SERVER_VERSION="5.0",t.MIN_SUPPORTED_WIRE_VERSION=8,t.MAX_SUPPORTED_WIRE_VERSION=27,t.MIN_SUPPORTED_QE_WIRE_VERSION=21,t.MIN_SUPPORTED_QE_SERVER_VERSION="7.0",t.MIN_SUPPORTED_RAW_DATA_WIRE_VERSION=27,t.MIN_SUPPORTED_RAW_DATA_SERVER_VERSION="8.2",t.OP_REPLY=1,t.OP_UPDATE=2001,t.OP_INSERT=2002,t.OP_QUERY=2004,t.OP_DELETE=2006,t.OP_COMPRESSED=2012,t.OP_MSG=2013},60892:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.makeBsonStringifiers=void 0,t.makePrintableBson=function(e){for(const[o,r]of Object.entries((0,t.makeBsonStringifiers)(e))){if(!(o in e))continue;const t=e[o];for(const e of[n,"inspect"])t.prototype[e]=r}};const n=Symbol.for("nodejs.util.inspect.custom");let r;function i(e,t){try{return r??(r=o(13390).inspect),r(e,{...t,maxArrayLength:r.defaultOptions.maxArrayLength})}catch{const t=Array.from(e);return t.length>100?`[${t.slice(0,100).join(", ")}, ... ${t.length-100} more items]`:`[${t.join(", ")}]`}}function s(e){return e.replace(/^\s*\S+\s*\(\d+\)\s*/,"")}function a(e){const t=e.prototype.inspect;return function(...e){return t.apply(this,e).replace(/^(\s*)(new )/,"$1")}}const c=e=>function(t,o){const n=a(e.Binary);switch(this.buffer[0]){case e.Binary.VECTOR_TYPE.Int8:return`Binary.fromInt8Array(new Int8Array(${s(i(this.toInt8Array(),{depth:t,...o}))}))`;case e.Binary.VECTOR_TYPE.Float32:return`Binary.fromFloat32Array(new Float32Array(${s(i(this.toFloat32Array(),{depth:t,...o}))}))`;case e.Binary.VECTOR_TYPE.PackedBit:{const e=0===this.buffer[1]?"":`, ${this.buffer[1]}`;return`Binary.fromPackedBits(new Uint8Array(${s(i(this.toPackedBits(),{depth:t,...o}))})${e})`}default:return n.call(this,t,o)}};t.makeBsonStringifiers=e=>{const t=c(e),o=a(e.Binary);return{ObjectId:a(e.ObjectId),ObjectID:a(e.ObjectId),DBRef:a(e.DBRef),MaxKey:a(e.MaxKey),MinKey:a(e.MinKey),Timestamp:a(e.Timestamp),BSONSymbol:a(e.BSONSymbol),Code:a(e.Code),Decimal128:a(e.Decimal128),Int32:a(e.Int32),Long:a(e.Long),Double:a(e.Double),BSONRegExp:a(e.BSONRegExp),Binary:function(...n){const r=this.toString("hex");switch(this.sub_type){case e.Binary.SUBTYPE_VECTOR:return t.apply(this,n);case e.Binary.SUBTYPE_MD5:return`MD5('${r}')`;case e.Binary.SUBTYPE_UUID:if(32===r.length)return`UUID('${/^(.{8})(.{4})(.{4})(.{4})(.{12})$/.exec(r).slice(1,6).join("-")}')`;default:return o.apply(this,n)}}}}},61347:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WaitingForSuitableServerEvent=t.ServerSelectionSucceededEvent=t.ServerSelectionFailedEvent=t.ServerSelectionStartedEvent=t.ServerSelectionEvent=void 0;const n=o(30306),r=o(34842);class i{constructor(e,t,o){this.selector=e,this.operation=o,this.topologyDescription=t}}t.ServerSelectionEvent=i,t.ServerSelectionStartedEvent=class extends i{constructor(e,t,o){super(e,t,o),this.name=r.SERVER_SELECTION_STARTED,this.message="Server selection started"}},t.ServerSelectionFailedEvent=class extends i{constructor(e,t,o,n){super(e,t,n),this.name=r.SERVER_SELECTION_FAILED,this.message="Server selection failed",this.failure=o}},t.ServerSelectionSucceededEvent=class extends i{constructor(e,t,o,i){super(e,t,i),this.name=r.SERVER_SELECTION_SUCCEEDED,this.message="Server selection succeeded";const{host:s,port:a}=n.HostAddress.fromString(o).toHostPort();this.serverHost=s,this.serverPort=a}},t.WaitingForSuitableServerEvent=class extends i{constructor(e,t,o,n){super(e,t,n),this.name=r.WAITING_FOR_SUITABLE_SERVER,this.message="Waiting for suitable server to become available",this.remainingTimeMS=o}}},62808:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StreamDescription=void 0;const n=o(77953),r=o(90648),i=o(32583),s=["minWireVersion","maxWireVersion","maxBsonObjectSize","maxMessageSizeBytes","maxWriteBatchSize","logicalSessionTimeoutMinutes"];t.StreamDescription=class{constructor(e,t){this.hello=null,this.address=e,this.type=r.ServerType.Unknown,this.minWireVersion=void 0,this.maxWireVersion=void 0,this.maxBsonObjectSize=16777216,this.maxMessageSizeBytes=48e6,this.maxWriteBatchSize=1e5,this.logicalSessionTimeoutMinutes=t?.logicalSessionTimeoutMinutes,this.loadBalanced=!!t?.loadBalanced,this.compressors=t&&t.compressors&&Array.isArray(t.compressors)?t.compressors:[],this.serverConnectionId=null}receiveResponse(e){if(null!=e){this.hello=e,this.type=(0,i.parseServerType)(e),this.serverConnectionId="connectionId"in e?this.parseServerConnectionID(e.connectionId):null;for(const t of s)null!=e[t]&&(this[t]=e[t]),"__nodejs_mock_server__"in e&&(this.__nodejs_mock_server__=e.__nodejs_mock_server__);e.compression&&(this.compressor=this.compressors.filter((t=>e.compression?.includes(t)))[0])}}parseServerConnectionID(e){return n.Long.isLong(e)?e.toBigInt():BigInt(e)}}},64543:(e,t,o)=>{var n=o(34110).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.constructShellBson=function({bsonLibrary:e,printWarning:t,assignMetadata:o,constructHelp:s}){const a=["Binary","Code","DBRef","Decimal128","Double","Int32","Long","MaxKey","MinKey","ObjectId","Timestamp","BSONSymbol","BSONRegExp"],c={};for(const t of a){if(!(t in e))throw new r.MongoshInternalError(`${t} does not exist in provided BSON package.`);const n=s?.(t);c[t]=n,"prototype"in e[t]&&o?.(e[t].prototype,{help:n,..."BSONSymbol"===t?{deprecated:!0,maxVersion:"1.6.0"}:{}})}const l={DBRef:(0,i.assignAll)((function(t,o,n,r){return(0,i.assertArgsDefinedType)([t,o,n],["string",!0,[void 0,"string"],[void 0,"object"]],"DBRef"),new e.DBRef(t,o,n,r)}),(0,i.pickWithExactKeyMatch)(e.DBRef,["prototype"])),bsonsize:function(t){return(0,i.assertArgsDefinedType)([t],["object"],"bsonsize"),e.calculateObjectSize(t)},MaxKey:(0,i.assignAll)((function(){return new e.MaxKey}),(0,i.pickWithExactKeyMatch)(e.MaxKey,["prototype"]),{toBSON:()=>new e.MaxKey}),MinKey:(0,i.assignAll)((function(){return new e.MinKey}),(0,i.pickWithExactKeyMatch)(e.MinKey,["prototype"]),{toBSON:()=>new e.MinKey}),ObjectId:(0,i.assignAll)((function(t){return(0,i.assertArgsDefinedType)([t],[[void 0,"string","number","object"]],"ObjectId"),"number"==typeof t?new e.ObjectId(e.ObjectId.generate(t)):new e.ObjectId(t)}),(0,i.pickWithExactKeyMatch)(e.ObjectId,["prototype","cacheHexString","generate","createFromTime","createFromHexString","createFromBase64","isValid"])),Timestamp:(0,i.assignAll)((function(t,o){return(0,i.assertArgsDefinedType)([t,o],[["number","object",void 0],[void 0,"number"]],"Timestamp"),"object"==typeof t&&null!==t&&"t"in t&&"i"in t?new e.Timestamp(t):void 0!==o||"number"==typeof t?new e.Timestamp({t,i:o??0}):new e.Timestamp(t)}),(0,i.pickWithExactKeyMatch)(e.Timestamp,["prototype","fromInt","fromNumber","fromBits","fromString","MAX_VALUE"])),Code:(0,i.assignAll)((function(t="",o){return(0,i.assertArgsDefinedType)([t,o],[[void 0,"string","function"],[void 0,"object"]],"Code"),new e.Code(t,o)}),(0,i.pickWithExactKeyMatch)(e.Code,["prototype"])),NumberDecimal:(0,i.assignAll)((function(o="0"){return(0,i.assertArgsDefinedType)([o],[["string","number","bson:Long","bson:Int32","bson:Decimal128"]],"NumberDecimal"),"number"==typeof o&&t("NumberDecimal: specifying a number as argument is deprecated and may lead to loss of precision, pass a string instead"),e.Decimal128.fromString(`${o}`)}),{prototype:e.Decimal128.prototype}),NumberInt:(0,i.assignAll)((function(t="0"){return t??(t="0"),(0,i.assertArgsDefinedType)([t],[["string","number","bson:Long","bson:Int32"]],"NumberInt"),new e.Int32(parseInt(`${t}`,10))}),{prototype:e.Int32.prototype}),NumberLong:(0,i.assignAll)((function(o="0"){return o??(o="0"),(0,i.assertArgsDefinedType)([o],[["string","number","bson:Long","bson:Int32"]],"NumberLong"),"number"==typeof o?(t("NumberLong: specifying a number as argument is deprecated and may lead to loss of precision, pass a string instead"),e.Long.fromNumber(o)):e.Long.fromString(`${o}`)}),{prototype:e.Long.prototype}),ISODate:function(e){if(void 0===e)return new Date;if("string"!=typeof e)return new Date(e);const t=/^(?<Y>\d{4})-?(?<M>\d{2})-?(?<D>\d{2})([T ](?<h>\d{2})(:?(?<m>\d{2})(:?((?<s>\d{2})(\.(?<ms>\d+))?))?)?(?<tz>Z|([+-])(\d{2}):?(\d{2})?)?)?$/.exec(e);if(null!==t&&void 0!==t.groups){const{Y:e,M:o,D:n,h:r,m:i,s,ms:a,tz:c}=t.groups,l=new Date(`${e}-${o}-${n}T${r||"00"}:${i||"00"}:${s||"00"}.${a||"000"}${c||"Z"}`);if(l.getTime()>=-621672192e5&&l.getTime()<=0xe677d21fdbff)return l}throw new r.MongoshInvalidInputError(`${JSON.stringify(e)} is not a valid ISODate`,r.CommonErrors.InvalidArgument)},BinData:(0,i.assignAll)((function(t,o){(0,i.assertArgsDefinedType)([t,o],["number","string"],"BinData");const r=n.from(o,"base64");return new e.Binary(r,t)}),{prototype:e.Binary.prototype}),HexData:(0,i.assignAll)((function(t,o){(0,i.assertArgsDefinedType)([t,o],["number","string"],"HexData");const r=n.from(o,"hex");return new e.Binary(r,t)}),{prototype:e.Binary.prototype}),UUID:(0,i.assignAll)((function(t){void 0===t&&(t=(new e.UUID).toString()),(0,i.assertArgsDefinedType)([t],["string"],"UUID");const o=n.from(t.replace(/-/g,""),"hex");return new e.Binary(o,e.Binary.SUBTYPE_UUID)}),{prototype:e.Binary.prototype}),LegacyJavaUUID:(0,i.assignAll)((function(t){void 0===t&&(t=(new e.UUID).toHexString()),(0,i.assertArgsDefinedType)([t],["string"],"LegacyJavaUUID");let o=String.prototype.replace.call(t,/[{}-]/g,(()=>"")),r=String.prototype.substring.call(o,0,16),s=String.prototype.substring.call(o,16,32);r=String.prototype.substring.call(r,14,16)+String.prototype.substring.call(r,12,14)+String.prototype.substring.call(r,10,12)+String.prototype.substring.call(r,8,10)+String.prototype.substring.call(r,6,8)+String.prototype.substring.call(r,4,6)+String.prototype.substring.call(r,2,4)+String.prototype.substring.call(r,0,2),s=String.prototype.substring.call(s,14,16)+String.prototype.substring.call(s,12,14)+String.prototype.substring.call(s,10,12)+String.prototype.substring.call(s,8,10)+String.prototype.substring.call(s,6,8)+String.prototype.substring.call(s,4,6)+String.prototype.substring.call(s,2,4)+String.prototype.substring.call(s,0,2),o=r+s;const a=n.from(o,"hex");return new e.Binary(a,e.Binary.SUBTYPE_UUID_OLD)}),{prototype:e.Binary.prototype}),LegacyCSharpUUID:(0,i.assignAll)((function(t){void 0===t&&(t=(new e.UUID).toHexString()),(0,i.assertArgsDefinedType)([t],["string"],"LegacyCSharpUUID");let o=String.prototype.replace.call(t,/[{}-]/g,(()=>""));o=String.prototype.substring.call(o,6,8)+String.prototype.substring.call(o,4,6)+String.prototype.substring.call(o,2,4)+String.prototype.substring.call(o,0,2)+(String.prototype.substring.call(o,10,12)+String.prototype.substring.call(o,8,10))+(String.prototype.substring.call(o,14,16)+String.prototype.substring.call(o,12,14))+String.prototype.substring.call(o,16,32);const r=n.from(o,"hex");return new e.Binary(r,e.Binary.SUBTYPE_UUID_OLD)}),{prototype:e.Binary.prototype}),LegacyPythonUUID:(0,i.assignAll)((function(t){void 0===t&&(t=(new e.UUID).toString()),(0,i.assertArgsDefinedType)([t],["string"],"LegacyPythonUUID");const o=n.from(t.replace(/-/g,""),"hex");return new e.Binary(o,e.Binary.SUBTYPE_UUID_OLD)}),{prototype:e.Binary.prototype}),MD5:(0,i.assignAll)((function(t){(0,i.assertArgsDefinedType)([t],["string"],"MD5");const o=n.from(t,"hex");return new e.Binary(o,e.Binary.SUBTYPE_MD5)}),{prototype:e.Binary.prototype}),Decimal128:(0,i.assignAll)((0,i.functionCtorWithoutProps)(e.Decimal128),(0,i.pickWithExactKeyMatch)(e.Decimal128,["prototype","fromString","fromStringWithRounding"])),BSONSymbol:(0,i.assignAll)((0,i.functionCtorWithoutProps)(e.BSONSymbol),(0,i.pickWithExactKeyMatch)(e.BSONSymbol,["prototype"])),Int32:(0,i.assignAll)((0,i.functionCtorWithoutProps)(e.Int32),(0,i.pickWithExactKeyMatch)(e.Int32,["prototype","fromString"])),Long:(0,i.assignAll)((0,i.functionCtorWithoutProps)(e.Long),(0,i.pickWithExactKeyMatch)(e.Long,["prototype","fromValue","isLong","fromBytesBE","fromBytesLE","fromBytes","fromString","fromStringStrict","fromBigInt","fromNumber","fromInt","fromBits","MIN_VALUE","MAX_VALUE","NEG_ONE","UONE","ONE","UZERO","ZERO","MAX_UNSIGNED_VALUE","TWO_PWR_24"])),Binary:(0,i.assignAll)((0,i.functionCtorWithoutProps)(e.Binary),(0,i.pickWithExactKeyMatch)(e.Binary,["prototype","createFromBase64","createFromHexString","fromInt8Array","fromFloat32Array","fromPackedBits","fromBits","BUFFER_SIZE","SUBTYPE_DEFAULT","SUBTYPE_FUNCTION","SUBTYPE_BYTE_ARRAY","SUBTYPE_UUID_OLD","SUBTYPE_UUID","SUBTYPE_MD5","SUBTYPE_ENCRYPTED","SUBTYPE_COLUMN","SUBTYPE_SENSITIVE","SUBTYPE_VECTOR","SUBTYPE_USER_DEFINED","VECTOR_TYPE"])),Double:(0,i.assignAll)((0,i.functionCtorWithoutProps)(e.Double),(0,i.pickWithExactKeyMatch)(e.Double,["prototype","fromString"])),BSONRegExp:(0,i.assignAll)((0,i.functionCtorWithoutProps)(e.BSONRegExp),(0,i.pickWithExactKeyMatch)(e.BSONRegExp,["prototype","parseOptions"])),EJSON:(0,i.pickWithExactKeyMatch)(e.EJSON,["parse","serialize","stringify","deserialize"])};for(const e of Object.keys(l)){const t=c[e]??s?.(e);t&&(l[e].help=()=>t,Object.setPrototypeOf(l[e].help,t))}return l};const r=o(92762),i=o(40083)},64578:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoCryptKMSRequestNetworkTimeoutError=t.MongoCryptAzureKMSRequestError=t.MongoCryptCreateEncryptedCollectionError=t.MongoCryptCreateDataKeyError=t.MongoCryptInvalidArgumentError=t.defaultErrorWrapper=t.MongoCryptError=void 0;const n=o(36997);class r extends n.MongoError{constructor(e,t={}){super(e,t)}get name(){return"MongoCryptError"}}t.MongoCryptError=r,t.defaultErrorWrapper=e=>new r(e.message,{cause:e}),t.MongoCryptInvalidArgumentError=class extends r{constructor(e){super(e)}get name(){return"MongoCryptInvalidArgumentError"}},t.MongoCryptCreateDataKeyError=class extends r{constructor(e,{cause:t}){super(`Unable to complete creating data keys: ${t.message}`,{cause:t}),this.encryptedFields=e}get name(){return"MongoCryptCreateDataKeyError"}},t.MongoCryptCreateEncryptedCollectionError=class extends r{constructor(e,{cause:t}){super(`Unable to create collection: ${t.message}`,{cause:t}),this.encryptedFields=e}get name(){return"MongoCryptCreateEncryptedCollectionError"}},t.MongoCryptAzureKMSRequestError=class extends r{constructor(e,t){super(e),this.body=t}get name(){return"MongoCryptAzureKMSRequestError"}},t.MongoCryptKMSRequestNetworkTimeoutError=class extends r{get name(){return"MongoCryptKMSRequestNetworkTimeoutError"}}},65070:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AUTH_MECHS_AUTH_SRC_EXTERNAL=t.AuthMechanism=void 0,t.AuthMechanism=Object.freeze({MONGODB_AWS:"MONGODB-AWS",MONGODB_DEFAULT:"DEFAULT",MONGODB_GSSAPI:"GSSAPI",MONGODB_PLAIN:"PLAIN",MONGODB_SCRAM_SHA1:"SCRAM-SHA-1",MONGODB_SCRAM_SHA256:"SCRAM-SHA-256",MONGODB_X509:"MONGODB-X509",MONGODB_OIDC:"MONGODB-OIDC"}),t.AUTH_MECHS_AUTH_SRC_EXTERNAL=new Set([t.AuthMechanism.MONGODB_GSSAPI,t.AuthMechanism.MONGODB_AWS,t.AuthMechanism.MONGODB_OIDC,t.AuthMechanism.MONGODB_X509])},65453:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OnDemandDocument=void 0;const n=o(77953);class r{constructor(e,t=0,o=!1,r){this.cache=Object.create(null),this.indexFound=Object.create(null),this.bson=e,this.offset=t,this.isArray=o,this.elements=r??(0,n.parseToElementsToArray)(this.bson,t)}isElementName(e,t){const o=t[2],n=t[1];if(e.length!==o)return!1;const r=n+o;for(let t=n,o=0;o<e.length&&t<r;o++,t++)if(this.bson[t]!==e.charCodeAt(o))return!1;return!0}getElement(e){const t=this.cache[e];if(!1===t)return null;if(null!=t)return t;if("number"==typeof e){if(this.isArray){if(e<this.elements.length){const t={element:this.elements[e],value:void 0};return this.cache[e]=t,this.indexFound[e]=!0,t}return null}return null}for(let t=0;t<this.elements.length;t++){const o=this.elements[t];if(!(t in this.indexFound)&&this.isElementName(e,o)){const n={element:o,value:void 0};return this.cache[e]=n,this.indexFound[t]=!0,n}}return this.cache[e]=!1,null}toJSValue(e,t){const o=e[0],i=e[3],s=e[4];if(t!==o)return null;switch(t){case n.BSONType.null:case n.BSONType.undefined:return null;case n.BSONType.double:return(0,n.getFloat64LE)(this.bson,i);case n.BSONType.int:return(0,n.getInt32LE)(this.bson,i);case n.BSONType.long:return(0,n.getBigInt64LE)(this.bson,i);case n.BSONType.bool:return Boolean(this.bson[i]);case n.BSONType.objectId:return new n.ObjectId(this.bson.subarray(i,i+12));case n.BSONType.timestamp:return new n.Timestamp((0,n.getBigInt64LE)(this.bson,i));case n.BSONType.string:return(0,n.toUTF8)(this.bson,i+4,i+s-1,!1);case n.BSONType.binData:{const e=(0,n.getInt32LE)(this.bson,i),t=this.bson[i+4];if(2===t){const t=(0,n.getInt32LE)(this.bson,i+1+4);if(t<0)throw new n.BSONError("Negative binary type element size found for subtype 0x02");if(t>e-4)throw new n.BSONError("Binary type with subtype 0x02 contains too long binary size");if(t<e-4)throw new n.BSONError("Binary type with subtype 0x02 contains too short binary size");return new n.Binary(this.bson.subarray(i+1+4+4,i+1+4+4+t),2)}return new n.Binary(this.bson.subarray(i+1+4,i+1+4+e),t)}case n.BSONType.date:return new Date(Number((0,n.getBigInt64LE)(this.bson,i)));case n.BSONType.object:return new r(this.bson,i);case n.BSONType.array:return new r(this.bson,i,!0);default:throw new n.BSONError(`Unsupported BSON type: ${t}`)}}size(){return this.elements.length}has(e){const t=this.cache[e];return!1!==t&&(null!=t||null!=this.getElement(e))}get(e,t,o){const r=this.getElement(e);if(null==r){if(!0===o)throw new n.BSONError(`BSON element "${e}" is missing`);return null}if(null==r.value){const i=this.toJSValue(r.element,t);if(null==i){if(!0===o)throw new n.BSONError(`BSON element "${e}" is missing`);return null}r.value=i}return r.value}getNumber(e,t){const o=this.get(e,n.BSONType.bool),r=null==o?null:o?1:0,i=this.get(e,n.BSONType.long),s=null==i?null:Number(i),a=r??s??this.get(e,n.BSONType.int)??this.get(e,n.BSONType.double);if(!0===t&&null==a)throw new n.BSONError(`BSON element "${e}" is missing`);return a}toObject(e){return(0,n.deserialize)(this.bson,{...e,index:this.offset,allowObjectSmallerThanBufferSize:!0})}toBytes(){const e=(0,n.getInt32LE)(this.bson,this.offset);return this.bson.subarray(this.offset,this.offset+e)}}t.OnDemandDocument=r},66022:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListCollectionsOperation=void 0;const n=o(72216),r=o(30306),i=o(41539),s=o(28947);class a extends i.CommandOperation{constructor(e,t,o){super(e,o),this.SERVER_COMMAND_RESPONSE_TYPE=n.CursorResponse,this.options={...o},delete this.options.writeConcern,this.db=e,this.filter=t,this.nameOnly=!!this.options.nameOnly,this.authorizedCollections=!!this.options.authorizedCollections,"number"==typeof this.options.batchSize&&(this.batchSize=this.options.batchSize),this.SERVER_COMMAND_RESPONSE_TYPE=this.explain?n.ExplainedCursorResponse:n.CursorResponse}get commandName(){return"listCollections"}buildCommandDocument(e){const t={listCollections:1,filter:this.filter,cursor:this.batchSize?{batchSize:this.batchSize}:{},nameOnly:this.nameOnly,authorizedCollections:this.authorizedCollections};return(0,r.maxWireVersion)(e)>=9&&void 0!==this.options.comment&&(t.comment=this.options.comment),t}handleOk(e){return e}}t.ListCollectionsOperation=a,(0,s.defineAspects)(a,[s.Aspect.READ_OPERATION,s.Aspect.RETRYABLE,s.Aspect.CURSOR_CREATING,s.Aspect.SUPPORTS_RAW_DATA])},66601:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.callback=void 0;const n=o(75227),r=o(15088),i="AZURE_FEDERATED_TOKEN_FILE",s="AWS_WEB_IDENTITY_TOKEN_FILE";t.callback=async()=>{let e;return e=r.env[i]?r.env[i]:r.env[s]?r.env[s]:"/var/run/secrets/kubernetes.io/serviceaccount/token",{accessToken:await(0,n.readFile)(e,"utf8")}}},67204:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionPoolMetrics=void 0;class o{constructor(){this.txnConnections=0,this.cursorConnections=0,this.otherConnections=0}static{this.TXN="txn"}static{this.CURSOR="cursor"}static{this.OTHER="other"}markPinned(e){e===o.TXN?this.txnConnections+=1:e===o.CURSOR?this.cursorConnections+=1:this.otherConnections+=1}markUnpinned(e){e===o.TXN?this.txnConnections-=1:e===o.CURSOR?this.cursorConnections-=1:this.otherConnections-=1}info(e){return`Timed out while checking out a connection from connection pool: maxPoolSize: ${e}, connections in use by cursors: ${this.cursorConnections}, connections in use by transactions: ${this.txnConnections}, connections in use by other operations: ${this.otherConnections}`}reset(){this.txnConnections=0,this.cursorConnections=0,this.otherConnections=0}}t.ConnectionPoolMetrics=o},67415:function(e,t,o){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=o(92762),i=n(o(72970)),s=n(o(70533)),a="en_US",c={en_US:s.default,de_DE:i.default};t.default=class{__(e){const t=this.translate(e);if(void 0===t)throw new r.MongoshInternalError(`Could not translate key ${JSON.stringify(e)}`);return t}constructor(e){this.locale=a,this.catalog=e||c[this.locale]}setLocale(e){Object.prototype.hasOwnProperty.call(c,e)?(this.locale=e,this.catalog=c[e]):(this.locale=a,this.catalog=c[a])}translate(e){return this.find(e)}translateApiHelp(e){const t=this.find(e);if(!t)return;if("string"==typeof t)return t;const{description:o="",link:n="",example:r="",returns:i=""}=t;return`${o}\n\n${n}\n\n${r}\n\n${i}`}find(e){return e.split(".").reduce(((e,t)=>e?e[t]:void 0),this.catalog)}}},67518:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Transaction=t.TxnState=void 0,t.isTransactionCommand=function(e){return!(!e.commitTransaction&&!e.abortTransaction)};const n=o(36997),r=o(86552),i=o(74891),s=o(71259);t.TxnState=Object.freeze({NO_TRANSACTION:"NO_TRANSACTION",STARTING_TRANSACTION:"STARTING_TRANSACTION",TRANSACTION_IN_PROGRESS:"TRANSACTION_IN_PROGRESS",TRANSACTION_COMMITTED:"TRANSACTION_COMMITTED",TRANSACTION_COMMITTED_EMPTY:"TRANSACTION_COMMITTED_EMPTY",TRANSACTION_ABORTED:"TRANSACTION_ABORTED"});const a={[t.TxnState.NO_TRANSACTION]:[t.TxnState.NO_TRANSACTION,t.TxnState.STARTING_TRANSACTION],[t.TxnState.STARTING_TRANSACTION]:[t.TxnState.TRANSACTION_IN_PROGRESS,t.TxnState.TRANSACTION_COMMITTED,t.TxnState.TRANSACTION_COMMITTED_EMPTY,t.TxnState.TRANSACTION_ABORTED],[t.TxnState.TRANSACTION_IN_PROGRESS]:[t.TxnState.TRANSACTION_IN_PROGRESS,t.TxnState.TRANSACTION_COMMITTED,t.TxnState.TRANSACTION_ABORTED],[t.TxnState.TRANSACTION_COMMITTED]:[t.TxnState.TRANSACTION_COMMITTED,t.TxnState.TRANSACTION_COMMITTED_EMPTY,t.TxnState.STARTING_TRANSACTION,t.TxnState.NO_TRANSACTION],[t.TxnState.TRANSACTION_ABORTED]:[t.TxnState.STARTING_TRANSACTION,t.TxnState.NO_TRANSACTION],[t.TxnState.TRANSACTION_COMMITTED_EMPTY]:[t.TxnState.TRANSACTION_COMMITTED_EMPTY,t.TxnState.NO_TRANSACTION]},c=new Set([t.TxnState.STARTING_TRANSACTION,t.TxnState.TRANSACTION_IN_PROGRESS]),l=new Set([t.TxnState.TRANSACTION_COMMITTED,t.TxnState.TRANSACTION_COMMITTED_EMPTY,t.TxnState.TRANSACTION_ABORTED]);t.Transaction=class{constructor(e){e=e??{},this.state=t.TxnState.NO_TRANSACTION,this.options={};const o=s.WriteConcern.fromOptions(e);if(o){if(0===o.w)throw new n.MongoTransactionError("Transactions do not support unacknowledged write concern");this.options.writeConcern=o}e.readConcern&&(this.options.readConcern=r.ReadConcern.fromOptions(e)),e.readPreference&&(this.options.readPreference=i.ReadPreference.fromOptions(e)),e.maxCommitTimeMS&&(this.options.maxTimeMS=e.maxCommitTimeMS),this._pinnedServer=void 0,this._recoveryToken=void 0}get server(){return this._pinnedServer}get recoveryToken(){return this._recoveryToken}get isPinned(){return!!this.server}get isStarting(){return this.state===t.TxnState.STARTING_TRANSACTION}get isActive(){return c.has(this.state)}get isCommitted(){return l.has(this.state)}transition(e){const o=a[this.state];if(o&&o.includes(e))return this.state=e,void(this.state!==t.TxnState.NO_TRANSACTION&&this.state!==t.TxnState.STARTING_TRANSACTION&&this.state!==t.TxnState.TRANSACTION_ABORTED||this.unpinServer());throw new n.MongoRuntimeError(`Attempted illegal state transition from [${this.state}] to [${e}]`)}pinServer(e){this.isActive&&(this._pinnedServer=e)}unpinServer(){this._pinnedServer=void 0}}},68950:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AuthProvider=t.AuthContext=void 0;const n=o(36997);t.AuthContext=class{constructor(e,t,o){this.reauthenticating=!1,this.connection=e,this.credentials=t,this.options=o}},t.AuthProvider=class{async prepare(e,t){return e}async reauth(e){if(e.reauthenticating)throw new n.MongoRuntimeError("Reauthentication already in progress.");try{e.reauthenticating=!0,await this.auth(e)}finally{e.reauthenticating=!1}}}},70533:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default={"browser-repl":{},build:{},"cli-repl":{args:{usage:"$ mongosh [options] [db address] [file names (ending in .js or .mongodb)]",options:"Options:",file:"Load the specified mongosh script",help:"Show this usage information",ipv6:"Enable IPv6 support (disabled by default)",host:"Server to connect to",port:"Port to connect to",buildInfo:"Show build information",version:"Show version information",quiet:"Silence output from the shell during the connection process",shell:"Run the shell after executing files",nodb:"Don't connect to mongod on startup - no 'db address' [arg] expected",deepInspect:"Force full depth inspection of server results (default: true if in interactive mode)",norc:"Will not run the '.mongoshrc.js' file on start up",eval:"Evaluate javascript",json:"Print result of --eval as Extended JSON, including errors",retryWrites:"Automatically retry write operations upon transient network errors (Default: true)",authenticationOptions:"Authentication Options:",username:"Username for authentication",password:"Password for authentication",authenticationDatabase:"User source (defaults to dbname)",authenticationMechanism:"Authentication mechanism",awsIamSessionToken:"AWS IAM Temporary Session Token ID",gssapiServiceName:"Service name to use when authenticating using GSSAPI/Kerberos",gssapiHostName:"Remote host name to use for purpose of GSSAPI/Kerberos authentication",sspiHostnameCanonicalization:"Specify the SSPI hostname canonicalization (none or forward, available on Windows)",sspiRealmOverride:"Specify the SSPI server realm (available on Windows)",tlsOptions:"TLS Options:",tls:"Use TLS for all connections",tlsCertificateKeyFile:"PEM certificate/key file for TLS",tlsCertificateKeyFilePassword:"Password for key in PEM file for TLS",tlsCAFile:"Certificate Authority file for TLS",tlsCRFile:"Certificate Revocation List file for TLS",tlsAllowInvalidHostnames:"Allow connections to servers with non-matching hostnames",tlsAllowInvalidCertificates:"Allow connections to servers with invalid certificates",tlsCertificateSelector:"TLS Certificate in system store (Windows and macOS only)",tlsCRLFile:"Specifies the .pem file that contains the Certificate Revocation List",tlsDisabledProtocols:"Comma separated list of TLS protocols to disable [TLS1_0,TLS1_1,TLS1_2]",tlsFIPSMode:"Enable the system TLS library's FIPS mode",apiVersionOptions:"API version options:",apiVersion:"Specifies the API version to connect with",apiStrict:"Use strict API version mode",apiDeprecationErrors:"Fail deprecated commands for the specified API version",fleOptions:"FLE Options:",awsAccessKeyId:"AWS Access Key for FLE Amazon KMS",awsSecretAccessKey:"AWS Secret Key for FLE Amazon KMS",awsSessionToken:"Optional AWS Session Token ID",keyVaultNamespace:"database.collection to store encrypted FLE parameters",kmsURL:"Test parameter to override the URL of the KMS endpoint",dbAddressOptions:"DB Address Examples:","dbAddress/foo":"Foo database on local machine","dbAddress/192/foo":"Foo database on 192.168.0.5 machine","dbAddress/192/host/foo":"Foo database on 192.168.0.5 machine on port 9999","dbAddress/connectionURI":"Connection string URI can also be used",fileNames:"File Names:",filenameDescription:"A list of files to run. Files must end in .js and will exit after unless --shell is specified.",examples:"Examples:",connectionExampleWithDatabase:"Start mongosh using 'ships' database on specified connection string:",moreInformation:"For more information on usage:",oidcOptions:"OIDC auth options:",oidcFlows:"Supported OIDC auth flows",oidcRedirectUri:"Local auth code flow redirect URL [http://localhost:27097/redirect]",oidcTrustedEndpoint:"Treat the cluster/database mongosh as a trusted endpoint",oidcIdTokenAsAccessToken:"Use ID tokens in place of access tokens for auth",oidcDumpTokens:"Debug OIDC by printing tokens to mongosh's output [redacted|include-secrets]",oidcNoNonce:"Don't send a nonce argument in the OIDC auth request"},"arg-parser":{"unknown-option":"Error parsing command line: unrecognized option:"},"cli-repl":{connecting:"Connecting to:",telemetry:"To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).",disableTelemetry:"You can opt-out by running the ",command:"command.",enabledTelemetry:"Telemetry is now enabled.",disabledTelemetry:"Telemetry is now disabled.",wiki:{info:"For mongosh info see:",link:"https://www.mongodb.com/docs/mongodb-shell/"},additionalErrorInfo:"Additional information",additionalErrorResult:"Result",additionalErrorViolations:"Violations",additionalErrorWriteErrors:"Write Errors",errorCausedBy:"Caused by"},"uri-generator":{"no-host-port":"If a full URI is provided, you cannot also specify --host or --port","invalid-host":"The --host argument contains an invalid character","host-list-port-mismatch":"The host list contains different ports than provided by --port","diverging-service-name":"Either the --gssapiServiceName parameter or the SERVICE_NAME authentication mechanism property in the connection string can be used but not both.","gssapi-service-name-unsupported":"The gssapiServiceName query parameter is not supported anymore. Please use the --gssapiServiceName argument or the SERVICE_NAME authentication mechanism property (e.g. ?authMechanismProperties=SERVICE_NAME:<value>)."}},"service-provider-browser":{},"service-provider-core":{},"service-provider-node-driver":{},"shell-api":{classes:{ShellLog:{help:{description:"Shell log methods",link:"#",attributes:{getPath:{description:"Gets a path to the current log file",example:"log.getPath()"},info:{description:"Writes a custom info message to the log file",example:'log.info("Custom info message")'},warn:{description:"Writes a custom warning message to the log file",example:'log.warn("Custom warning message")'},error:{description:"Writes a custom error message to the log file",example:'log.error("Custom error message")'},fatal:{description:"Writes a custom fatal message to the log file",example:'log.fatal("Custom fatal message")'},debug:{description:"Writes a custom debug message to the log file",example:'log.debug("Custom debug message")'}}}},ShellApi:{help:{description:"Shell Help",link:"https://mongodb.com/docs/manual/reference/method",attributes:{log:{description:"'log.info(<msg>)': Write a custom info/warn/error/fatal/debug message to the log file\n'log.getPath()': Gets a path to the current log file\n"},use:{description:"Set current database"},it:{description:"result of the last line evaluated; use to further iterate"},exit:{description:"Quit the MongoDB shell with exit/exit()/.exit"},quit:{description:"Quit the MongoDB shell with quit/quit()"},show:{description:"'show databases'/'show dbs': Print a list of all available databases\n'show collections'/'show tables': Print a list of all collections for current database\n'show profile': Prints system.profile information\n'show users': Print a list of all users for current database\n'show roles': Print a list of all roles for current database\n'show log <name>': Display log for current connection, if name is not set uses 'global'\n'show logs': Print all logger names."},connect:{description:"Create a new connection and return the Database object. Usage: connect(URI, username [optional], password [optional])",link:"https://mongodb.com/docs/manual/reference/method/connect"},Mongo:{description:"Create a new connection and return the Mongo object. Usage: new Mongo(URI, options [optional])",link:"https://mongodb.com/docs/manual/reference/method/Mongo/#Mongo"},version:{description:"Shell version",link:"https://mongodb.com/docs/manual/reference/method/version/"},load:{description:"Loads and runs a JavaScript file into the current shell environment",example:'load("path/to/file.js")'},enableTelemetry:{description:"Enables collection of anonymous usage data to improve the mongosh CLI"},disableTelemetry:{description:"Disables collection of anonymous usage data to improve the mongosh CLI"},passwordPrompt:{description:"Prompts the user for a password",link:"https://mongodb.com/docs/manual/reference/method/passwordPrompt/"},sleep:{description:"Sleep for the specified number of milliseconds",link:"https://mongodb.com/docs/manual/reference/method/sleep/",example:"sleep(5000)"},cls:{description:"Clears the screen like console.clear()"},print:{description:"Prints the contents of an object to the output",example:'print({ some: "value" })'},printjson:{description:"Alias for print()"},isInteractive:{description:"Returns whether the shell will enter or has entered interactive mode"},convertShardKeyToHashed:{description:"Returns the hashed value for the input using the same hashing function as a hashed index.",link:"https://www.mongodb.com/docs/manual/reference/method/convertShardKeyToHashed/"}}}},ShellConfig:{help:{description:"Shell configuration methods",attributes:{get:{description:"Get a configuration value with config.get(key)"},set:{description:"Change a configuration value with config.set(key, value)"},reset:{description:"Reset a configuration value to its default value with config.reset(key)"}}}},AggregationCursor:{help:{description:"Aggregation Class",attributes:{close:{link:"https://mongodb.com/docs/manual/reference/method/cursor.close",description:"Instructs the server to close a cursor and free associated server resources. The server will automatically close cursors that have no remaining results, as well as cursors that have been idle for a period of time and lack the cursor.noCursorTimeout() option.",example:"db.collection.aggregate(pipeline, options).close()"},forEach:{link:"https://mongodb.com/docs/manual/reference/method/cursor.forEach",description:"Iterates the cursor to apply a JavaScript function to each document from the cursor.",example:"db.collection.aggregate(pipeline, options).forEach(function)"},hasNext:{link:"https://mongodb.com/docs/manual/reference/method/cursor.hasNext",description:"cursor.hasNext() returns true if the cursor returned by the db.collection.aggregate() can iterate further to return more documents. NOTE: if the cursor is tailable with awaitData then hasNext will block until a document is returned. To check if a document is in the cursor's batch without waiting, use tryNext instead",example:"db.collection.aggregate(pipeline, options).hasNext()"},isClosed:{link:"https://mongodb.com/docs/manual/reference/method/cursor.isClosed",description:"Returns true if the cursor is closed.",example:"db.collection.aggregate(pipeline, options).isClosed()"},isExhausted:{link:"https://mongodb.com/docs/manual/reference/method/cursor.isExhausted",description:"cursor.isExhausted() returns true if the cursor is closed and there are no remaining objects in the batch.",example:"db.collection.aggregate(pipeline, options).isExhausted()"},itcount:{link:"https://mongodb.com/docs/manual/reference/method/cursor.itcount",description:"Counts the number of documents remaining in a cursor. itcount() is similar to cursor.count(), but actually executes the query on an existing iterator, exhausting its contents in the process.",example:"db.collection.aggregate(pipeline, options).itcount()"},map:{link:"https://mongodb.com/docs/manual/reference/method/cursor.map",description:"Applies the first argument, a function, to each document visited by the cursor and collects the return values from successive application into an array.",example:"db.collection.aggregate(pipeline, options).map(function)"},maxTimeMS:{link:"https://mongodb.com/docs/manual/reference/method/cursor.maxTimeMS",description:"Specifies a cumulative time limit in milliseconds for processing operations on a cursor.",example:"db.collection.aggregate(pipeline, options).maxTimeMS(timeLimit)"},next:{link:"https://mongodb.com/docs/manual/reference/method/cursor.next",description:"The next document in the cursor returned by the db.collection.aggregate() method. NOTE: if the cursor is tailable with awaitData then next will block until a document is returned. To check if a document is in the cursor's batch without waiting, use tryNext instead",example:"db.collection.aggregate(pipeline, options).next()"},tryNext:{description:"If a document is in the cursor's batch it will be returned, otherwise null will be returned"},explain:{link:"https://mongodb.com/docs/manual/reference/method/cursor.explain",description:"Provides information on the query plan for db.collection.aggregate() method.",example:"db.collection.aggregate(pipeline, options).explain([verbosity])"},objsLeftInBatch:{link:"https://mongodb.com/docs/manual/reference/method/cursor.objsLeftInBatch",description:"cursor.objsLeftInBatch() returns the number of documents remaining in the current batch.",example:"db.collection.aggregate(pipeline, options).objsLeftInBatch()"},toArray:{link:"https://mongodb.com/docs/manual/reference/method/cursor.toArray",description:"The toArray() method returns an array that contains all the documents from a cursor. The method iterates completely the cursor, loading all the documents into RAM and exhausting the cursor.",example:"db.collection.aggregate(pipeline, options).toArray()"},pretty:{description:"Deprecated. The shell provides auto-formatting so this method is no longer useful"},batchSize:{description:"Specifies the number of documents to return in each batch of the response from the MongoDB instance.",example:"db.collection.aggregate(pipeline, options).batchSize(10)"},projection:{link:"",description:"Sets a field projection for the query.",example:"db.collection.aggregate(pipeline, options).projection(field)"},sort:{link:"https://mongodb.com/docs/manual/reference/method/cursor.sort",description:"Specifies the order in which the query returns matching documents. You must apply sort() to the cursor before retrieving any documents from the database.",example:"db.collection.aggregate(pipeline, options).sort(sortDocument)"},skip:{link:"https://mongodb.com/docs/manual/reference/method/cursor.skip",description:"Call the cursor.skip() method on a cursor to control where MongoDB begins returning results. This approach may be useful in implementing paginated results.",example:"db.collection.aggregate(pipeline, options).skip(offsetNumber)"},disableBlockWarnings:{link:"",description:"Disables warnings for blocking operations on the cursor.",example:"db.collection.aggregate(pipeline, options).disableBlockWarnings()"}}}},BulkWriteResult:{help:{description:"BulkWriteResult Class",attributes:{acknowledged:{description:"Acknowledged returned from the server"},insertedCount:{description:"Number of documents inserted"},insertedIds:{description:"Array of ObjectIds inserted"},matchedCount:{description:"Number of documents matched"},modifiedCount:{description:"Number of documents modified"},deletedCount:{description:"Number of documents deleted"},upsertedCount:{description:"Number of documents upserted"},upsertedIds:{description:"Array of ObjectIds upserted"}}}},ClientBulkWriteResult:{help:{description:"ClientBulkWriteResult Class",attributes:{acknowledged:{description:"Acknowledged returned from the server"},insertedCount:{description:"Number of documents inserted"},matchedCount:{description:"Number of documents matched"},modifiedCount:{description:"Number of documents modified"},deletedCount:{description:"Number of documents deleted"},upsertedCount:{description:"Number of documents upserted"},insertResults:{description:"The results of each individual insert operation that was successfully performed"},updateResults:{description:"The results of each individual update operation that was successfully performed"},deleteResults:{description:"The results of each individual delete operation that was successfully performed."}}}},CommandResult:{help:{description:"CommandResult Class"}},InsertManyResult:{help:{description:"InsertManyResult Class",attributes:{acknowledged:{description:"Acknowledged returned from the server"},insertedIds:{description:"Array of ObjectIds inserted"}}}},InsertOneResult:{help:{description:"InsertOneResult Class",attributes:{acknowledged:{description:"Acknowledged returned from the server"},insertedId:{description:"ObjectId of document inserted"}}}},UpdateResult:{help:{description:"CommandResult Class",attributes:{acknowledged:{description:"Acknowledged returned from the server"},insertedId:{description:"ObjectId inserted"},matchedCount:{description:"Number of documents matched"},modifiedCount:{description:"Number of documents modified"},upsertedCount:{description:"Number of documents upserted"}}}},DeleteResult:{help:{description:"CommandResult Class",attributes:{acknowledged:{description:"Acknowledged returned from the server"},deletedCount:{description:"Number of documents deleted"}}}},ShowDbsResult:{help:{description:"ShowDatabasesResult Class"}},Collection:{help:{description:"Collection Class",attributes:{watch:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.watch",description:"Opens a change stream cursor on the collection",example:"const cursor = db.collection.watch(pipeline, options)"},aggregate:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.aggregate",description:"Calculates aggregate values for the data in a collection or a view.",example:"db.collection.aggregate(pipeline, options)"},bulkWrite:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.bulkWrite",description:"Performs multiple write operations with controls for order of execution.",example:"db.collection.bulkWrite(operations, options)"},countDocuments:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.countDocuments",description:"Returns the count of documents that match the query for a collection or view.",example:"db.collection.countDocuments(query, options)"},count:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.count",description:"Returns the count of documents that would match a find() query for the collection or view.",example:"db.collection.count(query, options)"},dataSize:{link:"hhttps://mongodb.com/docs/manual/reference/method/db.collection.dataSize",description:"This method provides a wrapper around the size output of the collStats (i.e. db.collection.stats()) command.",example:"db.collection.dataSize()"},deleteMany:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.deleteMany",description:"Removes all documents that match the filter from a collection.",example:"db.collection.deleteMany()"},deleteOne:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.deleteOne",description:"Removes a single document from a collection.",example:"db.collection.deleteOne(filter, options)"},distinct:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.distinct",description:"Finds the distinct values for a specified field across a single collection or view and returns the results in an array.",example:"db.collection.distinct(field, query, options)"},estimatedDocumentCount:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.estimatedDocumentCount",description:"Returns the count of all documents in a collection or view.",example:"db.collection.estimatedDocumentCount(options)"},find:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.find",description:"Selects documents in a collection or view.",example:"db.collection.find(query, projection, options)"},findAndModify:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.findAndModify",description:"Modifies and returns a single document.",example:"db.collection.findAndModify(spec)"},findOne:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.findOne",description:"Selects documents in a collection or view.",example:"db.collection.findOne(query, projection, options)"},findOneAndDelete:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.findOneAndDelete",description:"Deletes a single document based on the filter and sort criteria, returning the deleted document.",example:"db.collection.findOneAndDelete(filter, options)"},findOneAndReplace:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.findOneAndReplace",description:"Modifies and replaces a single document based on the filter and sort criteria.",example:"db.collection.findOneAndReplace(filter, replacement, options)"},findOneAndUpdate:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate",description:"Updates a single document based on the filter and sort criteria.",example:"db.collection.findOneAndUpdate(filter, update, options)"},getIndexes:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.getIndexes",description:"Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.",example:"db.collection.getIndexes()"},getIndices:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.getIndexes",description:"Alias for getIndexes. Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.",example:"db.collection.getIndices()"},insert:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.insert",description:"Inserts a document or documents into a collection.",example:"db.collection.insert(document, options)"},insertMany:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.insertMany",description:"Inserts multiple documents into a collection.",example:"db.collection.insertMany(documents, options)"},insertOne:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.insertOne",description:"Inserts a document into a collection.",example:"db.collection.insertOne(document, options)"},isCapped:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.isCapped",description:"Checks if a collection is capped",example:"db.collection.isCapped()"},remove:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.remove",description:"Removes documents from a collection.",example:"db.collection.remove(query, options)"},stats:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.stats",description:"Returns statistics about the collection.",example:"db.collection.stats(options)"},storageSize:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.storageSize",description:"The total amount of storage allocated to this collection for document storage.",example:"db.collection.storageSize()"},replaceOne:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.replaceOne",description:"Replaces a single document within the collection based on the filter.",example:"db.collection.replaceOne(filter, replacement, options)"},totalSize:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.totalSize",description:"The total size in bytes of the data in the collection plus the size of every index on the collection.",example:"db.collection.totalSize()"},update:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.update",description:"Modifies an existing document or documents in a collection.",example:"db.collection.update(query, update, options)"},updateMany:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.updateMany",description:"Updates all documents that match the specified filter for a collection.",example:"db.collection.updateMany(filter, update, options)"},compactStructuredEncryptionData:{link:"",description:"Compacts structured encryption data",example:"db.collection.compactStructuredEncryptionData()"},convertToCapped:{link:"",description:"calls {convertToCapped:'coll', size:maxBytes}} command",example:"db.coll.convertToCapped(10000)"},createIndexes:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.createIndexes",description:"Creates one or more indexes on a collection",example:"db.coll.createIndexes([{ category: 1 }], { name: 'index-1' })"},createIndex:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.createIndex",description:"Creates one index on a collection",example:"db.coll.createIndex({ category: 1 }, { name: 'index-1' })"},ensureIndex:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.ensureIndex",description:"Creates one index on a collection",example:"db.coll.ensureIndex({ category: 1 }, { name: 'index-1' })"},getDB:{link:"",description:"Get current database.",example:"db.collection.getDB()"},getIndexKeys:{link:"",description:"Return an array of key patterns for indexes defined on collection",example:"db.collection.getIndexKeys()"},getIndexSpecs:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.getIndexes",description:"Alias for getIndexes. Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.",example:"db.collection.getIndexSpecs()"},totalIndexSize:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.totalIndexSize",description:"Reports the total size used by the indexes on a collection.",example:"db.collection.totalIndexSize()"},dropIndexes:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.dropIndexes",description:"Drops the specified index or indexes (except the index on the _id field) from a collection.",example:"db.collection.dropIndexes()"},dropIndex:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.dropIndex",description:"Drops or removes the specified index from a collection.",example:"db.collection.dropIndex()"},reIndex:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.reIndex",description:"Rebuilds all existing indexes on a collection.",example:""},hideIndex:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.hideIndex",description:"Hides an existing index from the query planner.",example:'db.collection.hideIndex("index_1")'},unhideIndex:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.unhideIndex",description:"Unhides an existing index from the query planner.",example:'db.collection.unhideIndex("index_1")'},drop:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.drop",description:"Removes a collection or view from the database.",example:"db.students.drop()"},exists:{link:"",description:"Returns collection infos if the collection exists or null otherwise.",example:"db.coll.exists()"},getFullName:{link:"",description:"Returns the name of the collection prefixed with the database name.",example:"db.coll.getFullName()"},getName:{link:"",description:"Returns the name of the collection.",example:"db.coll.getName()"},renameCollection:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.renameCollection/",description:"Renames a collection.",example:'db.coll.renameCollection("newName")'},runCommand:{link:"",description:"Runs a db command with the given name where the first param is the collection name.",example:'db.collection.runCommand("text", { search: "searchKeywords" })'},explain:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.explain",description:"Returns information on the query plan.",example:"db.collection.explain().<method(...)>"},updateOne:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.updateOne",description:"Updates a single document within the collection based on the filter.",example:"db.collection.updateOne(filter, update, options)"},getMongo:{description:"Returns the Mongo object.",example:"db.collection.getMongo()"},latencyStats:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.latencyStats",description:"returns the $latencyStats aggregation for the collection. Takes an options document with an optional boolean 'histograms' field.",example:"db.latencyStats({ histograms: true })"},initializeUnorderedBulkOp:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.initializeUnorderedBulkOp",description:"Initializes an unordered bulk command. Returns an instance of Bulk",example:"db.coll.initializeUnorderedBulkOp()"},initializeOrderedBulkOp:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.initializeOrderedBulkOp",description:"Initializes an ordered bulk command. Returns an instance of Bulk",example:"db.coll.initializeOrderedBulkOp()"},getPlanCache:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.getPlanCache/",description:"Returns an interface to access the query plan cache for a collection. The interface provides methods to view and clear the query plan cache.",example:"db.coll.getPlanCache()"},validate:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.validate",description:"Calls the validate command. Default full value is false",example:"db.coll.validate(<full>)"},mapReduce:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.mapReduce",description:"Calls the mapReduce command",example:"db.coll.mapReduce(mapFn, reduceFn, options)"},getShardVersion:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.getShardVersion",description:"Calls the getShardVersion command",example:"db.coll.getShardVersion()"},getShardDistribution:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.getShardDistribution",description:"Prints the data distribution statistics for a sharded collection.",example:"db.coll.getShardDistribution()"},getShardLocation:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.getShardLocation",description:"Returns a document containing the shards where this collection is located as well as whether the collection itself is sharded.",example:"db.coll.getShardLocation()"},analyzeShardKey:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.analyzeShardKey",description:"Returns metrics for evaluating a shard key. That is, ‘key’ can be a candidate shard key for an unsharded or sharded collection, or the current shard key for a sharded collection.",example:"db.coll.analyzeShardKey(key)"},configureQueryAnalyzer:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.configureQueryAnalyzer",description:"Starts or stops collecting metrics about reads and writes against an unsharded or sharded collection.",example:"db.coll.configureQueryAnalyzer(options)"},checkMetadataConsistency:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.checkMetadataConsistency",description:"Returns a cursor with information about metadata inconsistencies",example:"db.coll.checkMetadataConsistency(<options>)"},getSearchIndexes:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.getSearchIndexes",description:"Returns an array that holds a list of documents that identify and describe the existing search indexes on the collection.",example:"db.coll.getSearchIndexes(<name>)"},createSearchIndexes:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.createSearchIndexes",description:"Creates one or more search indexes on a collection",example:"db.coll.createSearchIndexes(specs)"},createSearchIndex:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.createSearchIndex",description:"Creates one search indexes on a collection",example:"db.coll.createSearchIndex(<name>, definition)"},dropSearchIndex:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.dropSearchIndex",description:"Drops or removes the specified search index from a collection.",example:"db.coll.dropSearchIndex(name)"},updateSearchIndex:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.updateSearchIndex",description:"Updates the sepecified search index.",example:"db.coll.updateSearchIndex(name, definition)"}}}},ChangeStreamCursor:{iteration:{"no-cursor":"no cursor","type-it-for-more":'Type "it" for more'},help:{description:"Change Stream Cursor",attributes:{close:{description:"Instructs the server to close a cursor and free associated server resources."},isClosed:{description:"Returns true if the cursor is closed"},itcount:{description:"Returns the number of documents in the current batch. NOTE: this method exhausts the cursor batch"},getResumeToken:{description:"Returns the ResumeToken of the change stream"},hasNext:{description:"WARNING: on change streams this method will block unless the cursor is closed. Use tryNext to check if there are any documents in the batch. This is a breaking change"},next:{description:"WARNING: on change streams this method will block unless the cursor is closed. Use tryNext to get the next document in the batch. This is a breaking change"},tryNext:{description:"If there is a document in the change stream, it will be returned. Otherwise returns null."},isExhausted:{description:"This method is deprecated because because after closing a cursor, the remaining documents in the batch are no longer accessible. If you want to see if the cursor is closed use cursor.isClosed. If you want to see if there are documents left in the batch, use cursor.tryNext. This is a breaking change"},disableBlockWarnings:{link:"",description:"Disables warnings for blocking operations on the cursor."},batchSize:{description:"Not available on change streams"},maxTimeMS:{description:"Not available on change streams"}}}},Cursor:{iteration:{"no-cursor":"no cursor","type-it-for-more":'Type "it" for more'},help:{description:"Collection Cursor",attributes:{addOption:{link:"https://mongodb.com/docs/manual/reference/method/cursor.addOption",description:"Adds OP_QUERY wire protocol flags, such as the tailable flag, to change the behavior of queries. Accepts: DBQuery.Option fields tailable, slaveOk, noTimeout, awaitData, exhaust, partial.",example:"db.collection.find(query, projection, options).addOption(flag)"},allowPartialResults:{link:"https://mongodb.com/docs/manual/reference/method/cursor.allowPartialResults",description:"Sets the 'partial' option to true.",example:"db.collection.find(query, projection, options).allowPartialResults()"},allowDiskUse:{link:"https://mongodb.com/docs/manual/reference/method/cursor.allowDiskUse",description:"Sets the 'allowDiskUse' option. If no argument is passed, the default is true.",example:"db.collection.find(query, projection, options).sort(sort).allowDiskUse(false)"},batchSize:{link:"https://mongodb.com/docs/manual/reference/method/cursor.batchSize",description:"Specifies the number of documents to return in each batch of the response from the MongoDB instance. In most cases, modifying the batch size will not affect the user or the application, as the mongo shell and most drivers return results as if MongoDB returned a single batch.",example:"db.collection.find(query, projection, options).batchSize(10)"},close:{link:"https://mongodb.com/docs/manual/reference/method/cursor.close",description:"Instructs the server to close a cursor and free associated server resources. The server will automatically close cursors that have no remaining results, as well as cursors that have been idle for a period of time and lack the cursor.noCursorTimeout() option.",example:"db.collection.find(query, projection, options).close()"},collation:{link:"https://mongodb.com/docs/manual/reference/method/cursor.collation",description:"Specifies the collation for the cursor returned by the db.collection.find(). To use, append to the db.collection.find().",example:"db.collection.find(query, projection, options).collation(collationDocument)"},comment:{link:"https://mongodb.com/docs/manual/reference/method/cursor.comment",description:"Adds a comment field to the query.",example:"db.collection.find(query, projection, options).comment('Comment')"},count:{link:"https://mongodb.com/docs/manual/reference/method/cursor.count",description:"Counts the number of documents referenced by a cursor.",example:"db.collection.find(query, projection, options).count()"},explain:{link:"https://mongodb.com/docs/manual/reference/method/cursor.explain",description:"Provides information on the query plan for the db.collection.find() method.",example:"db.collection.find(query, projection, options).explain()"},forEach:{link:"https://mongodb.com/docs/manual/reference/method/cursor.forEach",description:"Iterates the cursor to apply a JavaScript function to each document from the cursor.",example:"db.collection.find(query, projection, options).forEach(function)"},getQueryPlan:{link:"https://mongodb.com/docs/manual/reference/method/cursor.explain",description:"Runs cursor.explain()",example:"db.collection.find(query, projection, options).getQueryPlan()"},hasNext:{link:"https://mongodb.com/docs/manual/reference/method/cursor.hasNext",description:"cursor.hasNext() returns true if the cursor returned by the db.collection.find() query can iterate further to return more documents. NOTE: if the cursor is tailable with awaitData then hasNext will block until a document is returned. To check if a document is in the cursor's batch without waiting, use tryNext instead",example:"db.collection.find(query, projection, options).hasNext()"},hint:{link:"https://mongodb.com/docs/manual/reference/method/cursor.hint",description:"Call this method on a query to override MongoDB’s default index selection and query optimization process. Use db.collection.getIndexes() to return the list of current indexes on a collection.",example:"db.collection.find(query, projection, options).hint(index)"},isClosed:{link:"https://mongodb.com/docs/manual/reference/method/cursor.isClosed",description:"Returns true if the cursor is closed.",example:"db.collection.find(query, projection, options).isClosed()"},isExhausted:{link:"https://mongodb.com/docs/manual/reference/method/cursor.isExhausted",description:"cursor.isExhausted() returns true if the cursor is closed and there are no remaining objects in the batch.",example:"db.collection.find(query, projection, options).isExhausted()"},itcount:{link:"https://mongodb.com/docs/manual/reference/method/cursor.itcount",description:"Counts the number of documents remaining in a cursor. itcount() is similar to cursor.count(), but actually executes the query on an existing iterator, exhausting its contents in the process.",example:"db.collection.find(query, projection, options).itcount()"},length:{link:"https://mongodb.com/docs/manual/reference/method/cursor.count",description:"Runs cursor.count()",example:"db.collection.find(query, projection, options).length()"},limit:{link:"https://mongodb.com/docs/manual/reference/method/cursor.limit",description:"Use the limit() method on a cursor to specify the maximum number of documents the cursor will return.",example:"db.collection.find(query, projection, options).limit(2)"},map:{link:"https://mongodb.com/docs/manual/reference/method/cursor.map",description:"Applies the first argument, a function, to each document visited by the cursor and collects the return values from successive application into an array.",example:"db.collection.find(query, projection, options).map(function)"},max:{link:"https://mongodb.com/docs/manual/reference/method/cursor.max",description:"Specifies the exclusive upper bound for a specific index in order to constrain the results of find(). max() provides a way to specify an upper bound on compound key indexes.",example:"db.collection.find(query, projection, options).max(indexBoundsDocument)"},maxScan:{link:"https://mongodb.com/docs/manual/reference/method/cursor.maxScan",description:"deprecated, non-functional"},maxTimeMS:{link:"https://mongodb.com/docs/manual/reference/method/cursor.maxTimeMS",description:"Specifies a cumulative time limit in milliseconds for processing operations on a cursor.",example:"db.collection.find(query, projection, options).maxTimeMS(timeLimit)"},maxAwaitTimeMS:{description:"Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise)",example:"db.collection.find(query, projection, options).maxAwaitTimeMS(timeLimit)"},min:{link:"https://mongodb.com/docs/manual/reference/method/cursor.min",description:"Specifies the inclusive lower bound for a specific index in order to constrain the results of find(). min() provides a way to specify lower bounds on compound key indexes.",example:"db.collection.find(query, projection, options).min(indexBoundsDocument)"},modifiers:{link:"",description:"Get query modifiers.",example:"db.collection.find(query, projection, options).modifiers()"},next:{link:"https://mongodb.com/docs/manual/reference/method/cursor.next",description:"The next document in the cursor returned by the db.collection.find() method. NOTE: if the cursor is tailable with awaitData then hasNext will block until a document is returned. To check if a document is in the cursor's batch without waiting, use tryNext instead",example:"db.collection.find(query, projection, options).next()"},tryNext:{description:"If a document is in the cursor's batch it will be returned, otherwise null will be returned"},noCursorTimeout:{link:"https://mongodb.com/docs/manual/reference/method/cursor.noCursorTimeout",description:"Instructs the server to avoid closing a cursor automatically after a period of inactivity.",example:"db.collection.find(query, projection, options).noCursorTimeout()"},objsLeftInBatch:{link:"https://mongodb.com/docs/manual/reference/method/cursor.objsLeftInBatch",description:"cursor.objsLeftInBatch() returns the number of documents remaining in the current batch.",example:"db.collection.find(query, projection, options).objsLeftInBatch()"},oplogReplay:{link:"",description:"Sets oplogReplay cursor flag to true.",example:"db.collection.find(query, projection, options).oplogReplay()"},projection:{link:"",description:"Sets a field projection for the query.",example:"db.collection.find(query, projection, options).projection(field)"},pretty:{description:"Deprecated. The shell provides auto-formatting so this method is no longer useful"},readConcern:{link:"https://mongodb.com/docs/manual/reference/method/cursor.readConcern",description:"Specify a read concern for the db.collection.find() method.",example:"db.collection.find(query, projection, options).readConcern(level)"},readonly:{link:"",description:"",example:""},readPref:{link:"https://mongodb.com/docs/manual/reference/method/cursor.readPref",description:"Append readPref() to a cursor to control how the client routes the query to members of the replica set.",example:"db.collection.find(query, projection, options).readPref(mode, tagSet)"},returnKey:{link:"https://mongodb.com/docs/manual/reference/method/cursor.returnKey",description:"Modifies the cursor to return index keys rather than the documents.",example:"db.collection.find(query, projection, options).returnKey()"},showDiskLoc:{link:"",description:"The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY style find.",example:"db.collection.find(query, projection, options).showDiskLoc()"},showRecordId:{link:"https://mongodb.com/docs/manual/reference/method/cursor.showRecordId",description:"Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection.",example:"db.collection.find(query, projection, options).showRecordId"},size:{link:"https://mongodb.com/docs/manual/reference/method/cursor.size",description:"A count of the number of documents that match the db.collection.find() query after applying any cursor.skip() and cursor.limit() methods.",example:"db.collection.find(query, projection, options).size()"},skip:{link:"https://mongodb.com/docs/manual/reference/method/cursor.skip",description:"Call the cursor.skip() method on a cursor to control where MongoDB begins returning results. This approach may be useful in implementing paginated results.",example:"db.collection.find(query, projection, options).skip(offsetNumber)"},snapshot:{link:"",description:"The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document",example:"db.collection.find(query, projection, options).snapshot()"},sort:{link:"https://mongodb.com/docs/manual/reference/method/cursor.sort",description:"Specifies the order in which the query returns matching documents. You must apply sort() to the cursor before retrieving any documents from the database.",example:"db.collection.find(query, projection, options).sort(sortDocument)"},tailable:{link:"https://mongodb.com/docs/manual/reference/method/cursor.tailable",description:"Marks the cursor as tailable.",example:"db.collection.find(query, projection, options).tailable({ awaitData: true })"},toArray:{link:"https://mongodb.com/docs/manual/reference/method/cursor.toArray",description:"The toArray() method returns an array that contains all the documents from a cursor. The method iterates completely the cursor, loading all the documents into RAM and exhausting the cursor.",example:"db.collection.find(query, projection, options).toArray()"},disableBlockWarnings:{link:"",description:"Disables warnings for blocking operations on the cursor.",example:"db.collection.find(query, projection, options).disableBlockWarnings()"}}}},Database:{help:{description:"Database Class",attributes:{sql:{link:"https://mongodb.com/docs/manual/reference/method/db.sql",description:"(Experimental) Runs a SQL query against Atlas Data Lake. Note: this is an experimental feature that may be subject to change in future releases.",example:'const cursor = db.sql("SELECT * FROM myCollection", options)'},watch:{link:"https://mongodb.com/docs/manual/reference/method/db.watch",description:"Opens a change stream cursor on the database",example:"const cursor = db.watch(pipeline, options)"},aggregate:{link:"https://mongodb.com/docs/manual/reference/method/db.aggregate",description:"Runs a specified admin/diagnostic pipeline which does not require an underlying collection.",example:"db.aggregate(pipeline, options)"},runCommand:{link:"https://mongodb.com/docs/manual/reference/method/db.runCommand",description:"Runs an arbitrary command on the database.",example:'db.runCommand({ text: "myCollection", search: "searchKeywords" })'},dropDatabase:{link:"https://mongodb.com/docs/manual/reference/method/db.dropDatabase",description:"Removes the current database, deleting the associated data files.",example:"db.dropDatabase([writeConcern])"},adminCommand:{link:"https://mongodb.com/docs/manual/reference/method/db.adminCommand",description:"Runs an arbitrary command against the admin database.",example:"db.adminCommand({ serverStatus: 1 })"},getCollectionInfos:{link:"https://mongodb.com/docs/manual/reference/method/db.getCollectionInfos",description:"Returns an array of documents with collection information, i.e. collection name and options, for the current database.",example:"db.getCollectionInfos()"},getCollectionNames:{link:"https://mongodb.com/docs/manual/reference/method/db.getCollectionNames",description:"Returns an array containing the names of all collections in the current database.",example:"db.getCollectionNames"},getSiblingDB:{link:"https://mongodb.com/docs/manual/reference/method/db.getSiblingDB",description:"Returns another database without modifying the db variable in the shell environment.",example:"db.getSiblingDB(name)"},getCollection:{link:"https://mongodb.com/docs/manual/reference/method/db.getCollection",description:"Returns a collection or a view object that is functionally equivalent to using the db.<collectionName>.",example:"db.getCollection(name)"},getMongo:{link:"https://mongodb.com/docs/manual/reference/method/db.getMongo/",description:"Returns the current database connection",example:"connection = db.getMongo()"},getName:{link:"https://mongodb.com/docs/manual/reference/method/db.getName",description:"Returns the name of the DB",example:"db.getName()"},createCollection:{link:"https://mongodb.com/docs/manual/reference/method/db.createCollection/",description:"Create new collection",example:"db.createCollection('collName')"},createEncryptedCollection:{link:"https://mongodb.com/docs/manual/reference/method/db.createEncryptedCollection/",description:"Creates a new collection with a list of encrypted fields each with unique and auto-created data encryption keys (DEKs). This is a utility function that internally utilises ClientEnryption.createEncryptedCollection.",example:'db.createEncryptedCollection( "collName", { "provider": "<kmsProvider>", "createCollectionOptions": { "encryptedFields": { ... }, ...<otherOptions> } })'},createView:{link:"https://mongodb.com/docs/manual/reference/method/db.createView/",description:"Create new view",example:"db.createView('viewName', 'source', [])"},createUser:{link:"https://mongodb.com/docs/manual/reference/method/db.createUser",description:"Creates a new user for the database on which the method is run. db.createUser() returns a duplicate user error if the user already exists on the database.",example:"db.createUser(user, writeConcern)"},updateUser:{link:"https://mongodb.com/docs/manual/reference/method/db.updateUser",description:"Updates the user’s profile on the database on which you run the method. An update to a field completely replaces the previous field’s values. This includes updates to the user’s roles array.",example:"db.updateUser(username, update, writeConcern)"},changeUserPassword:{link:"https://mongodb.com/docs/manual/reference/method/db.changeUserPassword",description:"Updates a user’s password. Run the method in the database where the user is defined, i.e. the database you created the user.",example:"db.changeUserPassword(username, password)"},logout:{link:"https://mongodb.com/docs/manual/reference/method/db.logout",description:"Ends the current authentication session. This function has no effect if the current session is not authenticated.",example:"db.logout()"},dropUser:{link:"https://mongodb.com/docs/manual/reference/method/db.dropUser",description:"Removes the user from the current database.",example:"db.dropUser(username, writeConcern)"},dropAllUsers:{link:"https://mongodb.com/docs/manual/reference/method/db.dropAllUsers",description:"Removes all users from the current database.",example:"db.dropAllUsers(writeConcern)"},auth:{link:"https://mongodb.com/docs/manual/reference/method/db.auth",description:"Allows a user to authenticate to the database from within the shell.",example:"db.auth(username, password)"},grantRolesToUser:{link:"https://mongodb.com/docs/manual/reference/method/db.grantRolesToUser",description:"Grants additional roles to a user.",example:'db.grantRolesToUser( "<username>", [ <roles> ], { <writeConcern> } )'},revokeRolesFromUser:{link:"https://mongodb.com/docs/manual/reference/method/db.revokeRolesFromUser",description:"Removes a one or more roles from a user on the current database.",example:'db.revokeRolesFromUser( "<username>", [ <roles> ], { <writeConcern> } )'},getUser:{link:"https://mongodb.com/docs/manual/reference/method/db.getUser",description:"Returns user information for a specified user. Run this method on the user’s database. The user must exist on the database on which the method runs.",example:"db.getUser(username, args)"},getUsers:{link:"https://mongodb.com/docs/manual/reference/method/db.getUsers",description:"Returns information for all the users in the database.",example:"db.getUsers(<options>)"},createRole:{link:"https://mongodb.com/docs/manual/reference/method/db.createRole",description:"Creates a new role.",example:"db.createRole(role, writeConcern)"},updateRole:{link:"https://mongodb.com/docs/manual/reference/method/db.updateRole",description:"Updates the role’s profile on the database on which you run the method. An update to a field completely replaces the previous field’s values.",example:"db.updateRole(rolename, update, writeConcern)"},dropRole:{link:"https://mongodb.com/docs/manual/reference/method/db.dropRole",description:"Removes the role from the current database.",example:"db.dropRole(rolename, writeConcern)"},dropAllRoles:{link:"https://mongodb.com/docs/manual/reference/method/db.dropAllRoles",description:"Removes all roles from the current database.",example:"db.dropAllRoles(writeConcern)"},grantRolesToRole:{link:"https://mongodb.com/docs/manual/reference/method/db.grantRolesToRole",description:"Grants additional roles to a role.",example:'db.grantRolesToRole( "<rolename>", [ <roles> ], { <writeConcern> } )'},revokeRolesFromRole:{link:"https://mongodb.com/docs/manual/reference/method/db.revokeRolesFromRole",description:"Removes a one or more roles from a role on the current database.",example:'db.revokeRolesFromRole( "<rolename>", [ <roles> ], { <writeConcern> } )'},grantPrivilegesToRole:{link:"https://mongodb.com/docs/manual/reference/method/db.grantPrivilegesToRole",description:"Grants additional privileges to a role.",example:'db.grantPrivilegesToRole( "<rolename>", [ <privileges> ], { <writeConcern> } )'},revokePrivilegesFromRole:{link:"https://mongodb.com/docs/manual/reference/method/db.revokePrivilegesFromRole",description:"Removes a one or more privileges from a role on the current database.",example:'db.revokeRolesFromRole( "<rolename>", [ <privileges> ], { <writeConcern> } )'},getRole:{link:"https://mongodb.com/docs/manual/reference/method/db.getRole",description:"Returns role information for a specified role. Run this method on the role’s database. The role must exist on the database on which the method runs.",example:"db.getRole(rolename, args)"},getRoles:{link:"https://mongodb.com/docs/manual/reference/method/db.getRoles",description:"Returns information for all the roles in the database.",example:"db.getRoles(<options>)"},currentOp:{link:"https://mongodb.com/docs/manual/reference/method/db.currentOp",description:"Runs an aggregation using $currentOp operator. Returns a document that contains information on in-progress operations for the database instance. For further information, see $currentOp.",example:"db.currentOp()"},killOp:{link:"https://mongodb.com/docs/manual/reference/method/db.killOp",description:"Calls the killOp command. Terminates an operation as specified by the operation ID. To find operations and their corresponding IDs, see $currentOp or db.currentOp().",example:"db.killOp(<options>)"},shutdownServer:{link:"https://mongodb.com/docs/manual/reference/method/db.shutdownServer",description:"Calls the shutdown command. Shuts down the current mongod or mongos process cleanly and safely. You must issue the db.shutdownServer() operation against the admin database.",example:"db.shutdownServer(<options>)"},fsyncLock:{link:"https://mongodb.com/docs/manual/reference/method/db.fsyncLock",description:"Calls the fsync command. Forces the mongod to flush all pending write operations to disk and locks the entire mongod instance to prevent additional writes until the user releases the lock with a corresponding db.fsyncUnlock() command.",example:"db.fsyncLock(<options>)"},fsyncUnlock:{link:"https://mongodb.com/docs/manual/reference/method/db.fsyncUnlock",description:"Calls the fsyncUnlock command. Reduces the lock taken by db.fsyncLock() on a mongod instance by 1.",example:"db.fsyncUnlock(<options>)"},version:{link:"https://mongodb.com/docs/manual/reference/method/db.version",description:"returns the db version. uses the buildinfo command",example:"db.version()"},serverBits:{link:"https://mongodb.com/docs/manual/reference/method/db.serverBits",description:"returns the db serverBits. uses the buildInfo command",example:"db.serverBits()"},isMaster:{link:"https://mongodb.com/docs/manual/reference/method/db.isMaster",description:"Calls the isMaster command",example:"db.isMaster()"},hello:{link:"https://mongodb.com/docs/manual/reference/method/db.hello",description:"Calls the hello command",example:"db.hello()"},rotateCertificates:{link:"https://mongodb.com/docs/manual/reference/method/db.rotateCertificates",description:"Calls the rotateCertificates command",example:"db.rotateCertificates()"},serverBuildInfo:{link:"https://mongodb.com/docs/manual/reference/method/db.serverBuildInfo",description:"returns the db serverBuildInfo. uses the buildInfo command",example:"db.serverBuildInfo()"},serverStatus:{link:"https://mongodb.com/docs/manual/reference/method/db.serverStatus",description:"returns the server stats. uses the serverStatus command",example:"db.serverStatus(<opts>)"},stats:{link:"https://mongodb.com/docs/manual/reference/method/db.stats",description:"returns the db stats. uses the dbStats command",example:"db.stats(<scale>) or db.stats({ scale: <scale> })"},hostInfo:{link:"https://mongodb.com/docs/manual/reference/method/db.hostInfo",description:"Calls the hostInfo command",example:"db.hostInfo()"},serverCmdLineOpts:{link:"https://mongodb.com/docs/manual/reference/method/db.serverCmdLineOpts",description:"returns the db serverCmdLineOpts. uses the getCmdLineOpts command",example:"db.serverCmdLineOpts()"},printCollectionStats:{link:"https://mongodb.com/docs/manual/reference/method/db.printCollectionStats",description:"Prints the collection.stats for each collection in the db.",example:"db.printCollectionStats(scale)"},getProfilingStatus:{link:"https://mongodb.com/docs/manual/reference/method/db.getProfilingStatus",description:"returns the db getProfilingStatus. uses the profile command",example:"db.getProfilingStatus()"},setProfilingLevel:{link:"https://mongodb.com/docs/manual/reference/method/db.setProfilingLevel",description:"returns the db setProfilingLevel. uses the profile command",example:"db.setProfilingLevel(level, <options>)"},setLogLevel:{link:"https://mongodb.com/docs/manual/reference/method/db.setLogLevel",description:"returns the db setLogLevel. uses the setParameter command",example:"db.setLogLevel(logLevel, <component>)"},getLogComponents:{link:"https://mongodb.com/docs/manual/reference/method/db.getLogComponents",description:"returns the db getLogComponents. uses the getParameter command",example:"db.getLogComponents()"},cloneDatabase:{link:"https://mongodb.com/docs/manual/reference/method/db.cloneDatabase",description:"deprecated, non-functional"},copyDatabase:{link:"https://mongodb.com/docs/manual/reference/method/db.copyDatabase",description:"deprecated, non-functional"},cloneCollection:{link:"https://mongodb.com/docs/manual/reference/method/db.cloneCollection",description:"deprecated, non-functional"},listCommands:{link:"https://mongodb.com/docs/manual/reference/method/db.listCommands",description:"Calls the listCommands command",example:"db.listCommands()"},commandHelp:{link:"https://mongodb.com/docs/manual/reference/method/db.commandHelp",description:"returns the db commandHelp. uses the passed in command with help: true",example:"db.commandHelp(<command>)"},getLastError:{link:"https://mongodb.com/docs/manual/reference/method/db.getLastError",description:"Calls the getLastError command",example:"db.getLastError(<w>, <wTimeout>)"},getLastErrorObj:{link:"https://mongodb.com/docs/manual/reference/method/db.getLastErrorObj",description:"Calls the getLastError command",example:"db.getLastErrorObj(<w>, <wTimeout>, <j>)"},printShardingStatus:{link:"https://mongodb.com/docs/manual/reference/method/db.printShardingStatus",description:"Calls sh.status(verbose)",example:"db.printShardingStatus(verbose?)"},printSecondaryReplicationInfo:{link:"https://mongodb.com/docs/manual/reference/method/db.printSecondaryReplicationInfo",description:"Prints secondary replicaset information",example:"db.printSecondaryReplicationInfo()"},printSlaveReplicationInfo:{link:"https://mongodb.com/docs/manual/reference/method/db.printSlaveReplicationInfo",description:"DEPRECATED. Use db.printSecondaryReplicationInfo",example:"db.printSlaveReplicationInfo()"},getReplicationInfo:{link:"https://mongodb.com/docs/manual/reference/method/db.getReplicationInfo",description:"Returns replication information",example:"db.getReplicationInfo()"},printReplicationInfo:{link:"https://mongodb.com/docs/manual/reference/method/db.printReplicationInfo",description:"Formats sh.getReplicationInfo",example:"db.printReplicationInfo()"},setSecondaryOk:{description:"This method is deprecated. Use db.getMongo().setReadPref() instead"},checkMetadataConsistency:{link:"https://mongodb.com/docs/manual/reference/method/db.checkMetadataConsistency",description:"Returns a cursor with information about metadata inconsistencies",example:"db.checkMetadataConsistency(<options>)"}}}},DBQuery:{help:{description:'Deprecated -- use config.set("displayBatchSize", value) instead of DBQuery.shellBatchSize = value'}},Explainable:{help:{description:"Explainable Class",attributes:{aggregate:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.explain",description:"Provides information on the query plan for db.collection.aggregate() method.",example:"db.coll.explain().aggregate()"},find:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.explain",description:"Returns information on the query plan.",example:"db.coll.explain().find()"},count:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.explain",description:"Returns information on the query plan for db.collection.count().",example:"db.coll.explain().count()"},remove:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.explain",description:"Returns information on the query plan for db.collection.remove().",example:"db.coll.explain().remove({})"},update:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.explain",description:"Returns information on the query plan for db.collection.update().",example:"db.coll.explain().update({}, { $inc: ${ a: 1 } })"},distinct:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.explain",description:"Returns information on the query plan for db.collection.distinct().",example:'db.coll.explain().distinct("_id")'},mapReduce:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.explain",description:"Returns information on the query plan for db.collection.mapReduce().",example:"db.coll.explain().mapReduce(map, reduce, options)"},findAndModify:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.explain",description:"Returns information on the query plan for db.collection.findAndModify().",example:"db.coll.explain().findAndModify({ query: { ... }, update: { ... } })"},findOneAndDelete:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.explain",description:"Returns information on the query plan for db.collection.findOneAndDelete().",example:"db.coll.explain().findOneAndDelete({ ... query ... })"},findOneAndReplace:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.explain",description:"Returns information on the query plan for db.collection.findOneAndReplace().",example:"db.coll.explain().findOneAndReplace({ ... query ... }, { ... replacement ... })"},findOneAndUpdate:{link:"https://mongodb.com/docs/manual/reference/method/db.collection.explain",description:"Returns information on the query plan for db.collection.findOneAndUpdate().",example:"db.coll.explain().findOneAndUpdate({ ... query ... }, { ... update operators ... })"},getCollection:{link:"",description:"Returns the explainable collection.",example:"db.coll.explain().getCollection()"},getVerbosity:{link:"",description:"Returns the explainable verbosity.",example:"db.coll.explain().getVerbosity()"},setVerbosity:{link:"",description:"Sets the explainable verbosity.",example:'db.coll.explain().setVerbosity("queryPlanner")'}}}},ExplainableCursor:{iteration:{"no-cursor":"no cursor","type-it-for-more":'Type "it" for more'},help:{description:"Explainable Cursor. See the Cursor class help methods for more information"}},RunCommandCursor:{help:{description:"RunCommandCursor Class",attributes:{batchSize:{description:"Specifies the number of documents to return in each batch of the response from the MongoDB instance."},close:{link:"https://mongodb.com/docs/manual/reference/method/cursor.close",description:"Instructs the server to close a cursor and free associated server resources. The server will automatically close cursors that have no remaining results, as well as cursors that have been idle for a period of time and lack the cursor.noCursorTimeout() option."},forEach:{link:"https://mongodb.com/docs/manual/reference/method/cursor.forEach",description:"Iterates the cursor to apply a JavaScript function to each document from the cursor."},hasNext:{link:"https://mongodb.com/docs/manual/reference/method/cursor.hasNext",description:"cursor.hasNext() returns true if the cursor returned by the db.collection.aggregate() can iterate further to return more documents. NOTE: if the cursor is tailable with awaitData then hasNext will block until a document is returned. To check if a document is in the cursor's batch without waiting, use tryNext instead"},isClosed:{link:"https://mongodb.com/docs/manual/reference/method/cursor.isClosed",description:"Returns true if the cursor is closed."},isExhausted:{link:"https://mongodb.com/docs/manual/reference/method/cursor.isExhausted",description:"cursor.isExhausted() returns true if the cursor is closed and there are no remaining objects in the batch."},itcount:{link:"https://mongodb.com/docs/manual/reference/method/cursor.itcount",description:"Counts the number of documents remaining in a cursor. itcount() is similar to cursor.count(), but actually executes the query on an existing iterator, exhausting its contents in the process."},map:{link:"https://mongodb.com/docs/manual/reference/method/cursor.map",description:"Applies the first argument, a function, to each document visited by the cursor and collects the return values from successive application into an array."},maxTimeMS:{link:"https://mongodb.com/docs/manual/reference/method/cursor.maxTimeMS",description:"Specifies a cumulative time limit in milliseconds for processing operations on a cursor."},next:{link:"https://mongodb.com/docs/manual/reference/method/cursor.next",description:"The next document in the cursor returned by the db.collection.aggregate() method. NOTE: if the cursor is tailable with awaitData then next will block until a document is returned. To check if a document is in the cursor's batch without waiting, use tryNext instead"},objsLeftInBatch:{link:"https://mongodb.com/docs/manual/reference/method/cursor.objsLeftInBatch",description:"cursor.objsLeftInBatch() returns the number of documents remaining in the current batch."},pretty:{description:"Deprecated. The shell provides auto-formatting so this method is no longer useful"},toArray:{link:"https://mongodb.com/docs/manual/reference/method/cursor.toArray",description:"The toArray() method returns an array that contains all the documents from a cursor. The method iterates completely the cursor, loading all the documents into RAM and exhausting the cursor."},tryNext:{description:"If a document is in the cursor's batch it will be returned, otherwise null will be returned"},disableBlockWarnings:{link:"",description:"Disables warnings for blocking operations on the cursor."}}}},ReplicaSet:{help:{description:"Replica Set Class",link:"https://mongodb.com/docs/manual/reference/method/js-replication/",attributes:{initiate:{link:"https://mongodb.com/docs/manual/reference/method/rs.initiate",description:"Initiates the replica set.",example:"rs.initiate()"},config:{link:"https://mongodb.com/docs/manual/reference/method/rs.conf",description:"Returns a document that contains the current replica set configuration.",example:"rs.config()"},reconfig:{link:"https://mongodb.com/docs/manual/reference/method/rs.reconfig",description:"Reconfigures an existing replica set, overwriting the existing replica set configuration.",example:"rs.reconfig()"},reconfigForPSASet:{link:"https://mongodb.com/docs/manual/reference/method/rs.reconfigForPSASet",description:"Reconfigures an existing replica set, overwriting the existing replica set configuration, if the reconfiguration is a transition from a Primary-Arbiter to a Primary-Secondary-Arbiter set.",example:"rs.reconfigForPSASet(indexOfNewMemberInMembersArray, config)"},conf:{link:"https://mongodb.com/docs/manual/reference/method/rs.conf",description:"Calls replSetConfig",example:"rs.conf()"},status:{link:"https://mongodb.com/docs/manual/reference/method/rs.status",description:"Calls replSetGetStatus",example:"rs.status()"},isMaster:{link:"https://mongodb.com/docs/manual/reference/method/rs.isMaster",description:"Calls isMaster",example:"rs.isMaster()"},hello:{link:"https://mongodb.com/docs/manual/reference/method/rs.hello",description:"Calls hello",example:"rs.hello()"},printSecondaryReplicationInfo:{link:"https://mongodb.com/docs/manual/reference/method/rs.printSecondaryReplicationInfo",description:"Calls db.printSecondaryReplicationInfo",example:"rs.printSecondaryReplicationInfo()"},printSlaveReplicationInfo:{link:"https://mongodb.com/docs/manual/reference/method/rs.printSlaveReplicationInfo",description:"DEPRECATED. Use rs.printSecondaryReplicationInfo",example:"rs.printSlaveReplicationInfo()"},printReplicationInfo:{link:"https://mongodb.com/docs/manual/reference/method/rs.printReplicationInfo",description:"Calls db.printReplicationInfo",example:"rs.printReplicationInfo()"},add:{link:"https://mongodb.com/docs/manual/reference/method/rs.add",description:"Adds replica set member to replica set.",example:"rs.add(hostport, arbiterOnly?)"},addArb:{link:"https://mongodb.com/docs/manual/reference/method/rs.addArb",description:"Calls rs.add with arbiterOnly=true",example:"rs.addArb(hostname)"},remove:{link:"https://mongodb.com/docs/manual/reference/method/rs.remove",description:"Removes a replica set member.",example:"rs.remove(hostname)"},freeze:{link:"https://mongodb.com/docs/manual/reference/method/rs.freeze",description:"Prevents the current member from seeking election as primary for a period of time. Uses the replSetFreeze command",example:"rs.freeze(secs)"},stepDown:{link:"https://mongodb.com/docs/manual/reference/method/rs.stepDown",description:"Causes the current primary to become a secondary which forces an election. If no stepDownSecs is provided, uses 60 seconds. Uses the replSetStepDown command",example:"rs.stepDown(stepDownSecs?, catchUpSecs?)"},syncFrom:{link:"https://mongodb.com/docs/manual/reference/method/rs.syncFrom",description:"Sets the member that this replica set member will sync from, overriding the default sync target selection logic.",example:"rs.syncFrom(host)"},secondaryOk:{description:"This method is deprecated. Use db.getMongo().setReadPref() instead"}}}},Shard:{help:{description:"The Shard Class",attributes:{enableSharding:{link:"https://mongodb.com/docs/manual/reference/method/sh.enableSharding",description:"Enables sharding on a specific database. Uses the enableSharding command",example:"sh.enableSharding(database, primaryShard?)"},shardCollection:{link:"https://mongodb.com/docs/manual/reference/method/sh.shardCollection",description:"Enables sharding for a collection. Uses the shardCollection command",example:"sh.shardCollection(namespace, key, unique?, options?)"},reshardCollection:{link:"https://mongodb.com/docs/manual/reference/method/sh.reshardCollection",description:"Enables sharding for a collection. Uses the reshardCollection command",example:"sh.reshardCollection(namespace, key, unique?, options?)"},commitReshardCollection:{link:"https://mongodb.com/docs/manual/reference/method/sh.commitReshardCollection",description:"Commits the current reshardCollection on a given collection",example:"sh.commitReshardCollection(namespace)"},abortReshardCollection:{link:"https://mongodb.com/docs/manual/reference/method/sh.abortReshardCollection",description:"Abort the current reshardCollection on a given collection",example:"sh.abortReshardCollection(namespace)"},status:{link:"https://mongodb.com/docs/manual/reference/method/sh.status",description:"Prints a formatted report of the sharding configuration and the information regarding existing chunks in a sharded cluster. The default behavior suppresses the detailed chunk information if the total number of chunks is greater than or equal to 20.",example:"sh.status(verbose?)"},addShard:{link:"https://mongodb.com/docs/manual/reference/method/sh.addShard",description:"Adds a shard to a sharded cluster. Uses the addShard command",example:"sh.addShard(url)"},addShardToZone:{link:"https://mongodb.com/docs/manual/reference/method/sh.addShardToZone",description:"Associates a shard to a zone. Uses the addShardToZone command",example:"sh.addShardToZone(shard, zone)"},addShardTag:{link:"https://mongodb.com/docs/manual/reference/method/sh.addShardTag",description:"3.4+ only. Calls addShardTag for a sharded DB. Aliases to sh.addShardToZone().",example:"sh.addShardTag(shard, tag)"},updateZoneKeyRange:{link:"https://mongodb.com/docs/manual/reference/method/sh.updateZoneKeyRange",description:"Associates a range of shard keys to a zone. Uses the updateZoneKeyRange command",example:"sh.updateZoneKeyRange(ns, min, max, zone)"},addTagRange:{link:"https://mongodb.com/docs/manual/reference/method/sh.addTagRange",description:"3.4+ only. Adds a tag range for a sharded DB. This method aliases to sh.updateZoneKeyRange()",example:"sh.addTagRange(ns, min, max, zone)"},removeRangeFromZone:{link:"https://mongodb.com/docs/manual/reference/method/sh.removeRangeFromZone",description:"3.4+ only. Removes an association between a range of shard keys and a zone.",example:"sh.removeRangeFromZone(ns, min, max)"},removeTagRange:{link:"https://mongodb.com/docs/manual/reference/method/sh.removeTagRange",description:"3.4+ only. Removes tag range for a sharded DB. Aliases to sh.removeRangeFromZone",example:"sh.removeTagRange(ns, min, max)"},removeShardFromZone:{link:"https://mongodb.com/docs/manual/reference/method/sh.removeShardFromZone",description:"3.4+ only. Removes the association between a shard and a zone. Uses the removeShardFromZone command",example:"sh.removeShardFromZone(shard, zone)"},removeShardTag:{link:"https://mongodb.com/docs/manual/reference/method/sh.removeShardTag",description:"3.4+ only. Removes a shard tag for a sharded DB. Aliases to sh.removeShardFromZone",example:"sh.removeShardTag(shard, zone)"},enableAutoSplit:{link:"https://mongodb.com/docs/manual/reference/method/sh.enableAutoSplit",description:"Enables auto-splitting for the sharded cluster. Calls update on the config.settings collection",example:"sh.enableAutoSplit()"},disableAutoSplit:{link:"https://mongodb.com/docs/manual/reference/method/sh.disableAutoSplit",description:"Disables auto-splitting for the sharded cluster. Calls update on the config.settings collection",example:"sh.disableAutoSplit()"},splitAt:{link:"https://mongodb.com/docs/manual/reference/method/sh.splitAt",description:"Divides an existing chunk into two chunks using a specific value of the shard key as the dividing point. Uses the split command",example:"sh.splitAt(ns, query)"},splitFind:{link:"https://mongodb.com/docs/manual/reference/method/sh.splitFind",description:"Splits a chunk at the shard key value specified by the query at the median. Uses the split command",example:"sh.splitFind(ns, query)"},moveChunk:{link:"https://mongodb.com/docs/manual/reference/method/sh.moveChunk",description:"Moves the chunk that contains the document specified by the query to the destination shard. Uses the moveChunk command",example:"sh.moveChunk(ns, query, destination)"},moveRange:{link:"https://mongodb.com/docs/manual/reference/method/sh.moveRange",description:"Moves a range of documents specified by the min and max keys to the destination shard. Uses the moveRange command",example:"sh.moveRange(ns, toShard, min?, max?)"},balancerCollectionStatus:{link:"https://mongodb.com/docs/manual/reference/method/sh.balancerCollectionStatus",description:"Returns information on whether the chunks of a sharded collection are balanced. Uses the balancerCollectionStatus command",example:"sh.balancerCollectionStatus(ns)"},enableBalancing:{link:"https://mongodb.com/docs/manual/reference/method/sh.enableBalancing",description:"Activates the sharded collection balancer process.",example:"sh.enableBalancing(ns)"},disableBalancing:{link:"https://mongodb.com/docs/manual/reference/method/sh.disableBalancing",description:"Disable balancing on a single collection in a sharded database. Does not affect balancing of other collections in a sharded cluster.",example:"sh.disableBalancing(ns)"},enableMigrations:{link:"https://mongodb.com/docs/manual/reference/method/sh.enableMigrations",description:"Enables migrations for a specific collection. Uses `setAllowMigrations` admin command.",example:"sh.enableMigrations(ns)"},disableMigrations:{link:"https://mongodb.com/docs/manual/reference/method/sh.disableMigrations",description:"Disables migrations for a specific collection. Uses `setAllowMigrations` admin command.",example:"sh.disableMigrations(ns)"},getBalancerState:{link:"https://mongodb.com/docs/manual/reference/method/sh.getBalancerState",description:"Returns true when the balancer is enabled and false if the balancer is disabled. This does not reflect the current state of balancing operations: use sh.isBalancerRunning() to check the balancer’s current state.",example:"sh.getBalancerState()"},isBalancerRunning:{link:"https://mongodb.com/docs/manual/reference/method/sh.isBalancerRunning",description:"Returns true if the balancer process is currently running and migrating chunks and false if the balancer process is not running. Uses the balancerStatus command",example:"sh.isBalancerRunning()"},startBalancer:{link:"https://mongodb.com/docs/manual/reference/method/sh.startBalancer",description:"Enables the balancer. Uses the balancerStart command",example:"sh.startBalancer(timeout)"},stopBalancer:{link:"https://mongodb.com/docs/manual/reference/method/sh.stopBalancer",description:"Disables the balancer. uses the balancerStop command",example:"sh.stopBalancer(timeout)"},setBalancerState:{link:"https://mongodb.com/docs/manual/reference/method/sh.setBalancerState",description:"Calls sh.startBalancer if state is true, otherwise calls sh.stopBalancer",example:"sh.setBalancerState(state)"},getShardedDataDistribution:{description:"Returns data-size distribution information for all existing sharded collections",example:"sh.getShardedDataDistribution()"},startAutoMerger:{link:"https://mongodb.com/docs/manual/reference/method/sh.startAutoMerger",description:"Globally enable auto-merger (active only if balancer is up)",example:"sh.startAutoMerger()"},stopAutoMerger:{link:"https://mongodb.com/docs/manual/reference/method/sh.stopAutoMerger",description:"Globally disable auto-merger",example:"sh.stopAutoMerger()"},isAutoMergerEnabled:{link:"https://mongodb.com/docs/manual/reference/method/sh.isAutoMergerEnabled",description:"Returns whether the auto-merger is enabled",example:"sh.isAutoMergerEnabled()"},disableAutoMerger:{link:"https://mongodb.com/docs/manual/reference/method/sh.disableAutoMerger",description:"Disable auto-merging on one collection",example:"sh.disableAutoMerger(ns)"},enableAutoMerger:{link:"https://mongodb.com/docs/manual/reference/method/sh.enableAutoMerger",description:"Re-enable auto-merge on one collection",example:"sh.enableAutoMerger(ns)"},checkMetadataConsistency:{link:"https://mongodb.com/docs/manual/reference/method/sh.checkMetadataConsistency",description:"Returns a cursor with information about metadata inconsistencies",example:"sh.checkMetadataConsistency(<options>)"},shardAndDistributeCollection:{description:"Shards a collection and then immediately reshards the collection to the same shard key.",example:"sh.shardAndDistributeCollection(ns, key, unique?, options?)"},moveCollection:{link:"https://mongodb.com/docs/manual/reference/method/sh.moveCollection",description:"Moves a single unsharded collection to a different shard.",example:"sh.moveCollection(ns, toShard)"},abortMoveCollection:{link:"https://mongodb.com/docs/manual/reference/method/sh.abortMoveCollection",description:"Abort the current moveCollection operation on a given collection",example:"sh.abortMoveCollection(ns)"},unshardCollection:{link:"https://mongodb.com/docs/manual/reference/method/sh.unshardCollection",description:"Unshard the given collection and move all data to the given shard.",example:"sh.unshardCollection(ns, toShard)"},abortUnshardCollection:{link:"https://mongodb.com/docs/manual/reference/method/sh.abortUnshardCollection",description:"Abort the current unshardCollection operation on a given collection",example:"sh.abortUnshardCollection(ns)"},listShards:{link:"https://mongodb.com/docs/manual/reference/method/sh.listShards",description:"Returns a list of the configured shards in a sharded cluster",example:"sh.listShards()"},isConfigShardEnabled:{link:"https://mongodb.com/docs/manual/reference/method/sh.isConfigShardEnabled",description:"Returns a document with an `enabled: <boolean>` field indicating whether the cluster is configured as embedded config server cluster. If it is, then the config shard host and tags are also returned.",example:"sh.isConfigShardEnabled()"}}}},Session:{help:{description:"The Session Class. Represents a server session",link:"https://mongodb.com/docs/manual/reference/method/Session/",attributes:{getDatabase:{link:"https://mongodb.com/docs/manual/reference/method/Session/#Session.getDatabase",description:"Returns a database class that will pass the session to the server with every command"},advanceOperationTime:{link:"https://mongodb.com/docs/manual/reference/method/Session/#Session.advanceOperationTime",description:"Updates the operation time"},endSession:{link:"https://mongodb.com/docs/manual/reference/method/Session/#Session.endSession",description:"Ends the session"},hasEnded:{link:"https://mongodb.com/docs/manual/reference/method/Session/#Session.hasEnded",description:"Returns a boolean that specifies whether the session has ended."},getClusterTime:{link:"https://mongodb.com/docs/manual/reference/method/Session/#Session.getClusterTime",description:"Returns the most recent cluster time as seen by the session. Applicable for replica sets and sharded clusters only."},getOperationTime:{link:"https://mongodb.com/docs/manual/reference/method/Session/#Session.getOperationTime",description:"Returns the timestamp of the last acknowledged operation for the session."},getOptions:{link:"https://mongodb.com/docs/manual/reference/method/Session/#Session.getOptions",description:"Returns the options object passed to startSession"},startTransaction:{link:"https://mongodb.com/docs/manual/reference/method/Session.startTransaction/#Session.startTransaction",description:"Starts a multi-document transaction for the session."},commitTransaction:{link:"https://mongodb.com/docs/manual/reference/method/Session.commitTransaction/#Session.commitTransaction",description:"Commits the session’s transaction."},abortTransaction:{link:"https://mongodb.com/docs/manual/reference/method/Session.abortTransaction/#Session.abortTransaction",description:"Aborts the session’s transaction."},withTransaction:{link:"https://mongodb.com/docs/manual/reference/method/Session.abortTransaction/#Session.withTransaction",description:"Run a function within a transaction context.",example:'session.withTransaction(() => { session.getDatabase("test").test.insertOne({ doc: 1 }); })'},advanceClusterTime:{description:"Advances the clusterTime for a Session to the provided clusterTime."}}}},Mongo:{help:{description:"The Mongo Class. Represents a connection to a server",link:"https://mongodb.com/docs/manual/reference/method/Mongo/#Mongo",attributes:{watch:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.watch",description:"Opens a change stream cursor on the connection",example:"const cursor = db.getMongo().watch(pipeline, options)"},startSession:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.startSession/",description:"Starts a session for the connection."},bulkWrite:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.bulkWrite",description:"Performs multiple write operations across databases and collections with controls for order of execution.",example:"db.getMongo().bulkWrite(operations, options)"},getCollection:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.getCollection",description:"Returns the specified Collection of the Mongo object.",example:'const collection = db.getMongo().getCollection("databaseName.collectionName")'},getDB:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.getDB",description:"Returns the specified Database of the Mongo object."},getDBs:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.getDBs",description:"Returns information about all databases. Uses the listDatabases command."},getDBNames:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.getDBs",description:"Returns an array of all database names. Uses the listDatabases command.",example:"db.getMongo().getDBNames().map(name => db.getSiblingDB(name).getCollectionNames())"},getURI:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.getURI",description:"Returns the connection string for current session"},connect:{link:"https://mongodb.com/docs/manual/reference/method/connect",description:"Creates a connection to a MongoDB instance and returns the reference to the database."},close:{description:"Closes a Mongo object, disposing of related resources and closing the underlying connection."},getReadConcern:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.getReadConcern",description:"Returns the ReadConcern set for the connection.",example:"db.getMongo().getReadConcern()"},getWriteConcern:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.getWriteConcern",description:"Returns the WriteConcern set for the connection.",example:"db.getMongo().getWriteConcern()"},getReadPref:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.getReadPref",description:"Returns the ReadPreference set for the connection.",example:"db.getMongo().getReadPref()"},getReadPrefMode:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.getReadPrefMode",description:"Returns the ReadPreference Mode set for the connection.",example:"db.getMongo().getReadPrefMode()"},getReadPrefTagSet:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.getReadPrefTagSet",description:"Returns the ReadPreference TagSet set for the connection.",example:"db.getMongo().getReadPrefTagSet()"},setReadPref:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.setReadPref",description:"Sets the ReadPreference for the connection",example:"db.getMongo().setReadPref(mode, tagSets, hedgeOptions)"},setReadConcern:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.setReadConcern",description:"Sets the ReadConcern for the connection",example:"db.getMongo().setReadConcern(level)"},setWriteConcern:{link:"https://mongodb.com/docs/manual/reference/method/Mongo.setWriteConcern",description:"Sets the WriteConcern for the connection",example:"db.getMongo().setWriteConcern('majority')"},setCausalConsistency:{description:"This method is deprecated. It is not possible to set causal consistency for an entire connection due to driver limitations, use startSession({causalConsistency: <>}) instead."},setSlaveOk:{description:"This method is deprecated"},setSecondaryOk:{description:"This method is deprecated. Use .setReadPref() instead"},isCausalConsistency:{description:"This method is deprecated. Causal consistency for drivers is set via Mongo.startSession and can be checked via session.getOptions. The default value is true"},getKeyVault:{description:"Returns the KeyVault object for the current database connection. The KeyVault object supports data encryption key management for Client-side field level encryption.",link:"https://mongodb.com/docs/manual/reference/method/getKeyVault/#getKeyVault"},getClientEncryption:{description:"Returns the ClientEncryption object for the current database collection. The ClientEncryption object supports explicit (manual) encryption and decryption of field values for Client-Side field level encryption.",link:"https://mongodb.com/docs/manual/reference/method/getClientEncryption/#getClientEncryption"},convertShardKeyToHashed:{description:"Returns the hashed value for the input using the same hashing function as a hashed index.",link:"https://www.mongodb.com/docs/manual/reference/method/convertShardKeyToHashed/"}}}},DBRef:{help:{description:"The DBRef BSON Class.",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.DBRef.html",example:"new DBRef(namespace: string, oid: ObjectId, db: string [optional])"},attributes:{}},MaxKey:{help:{description:"The MaxKey BSON Class.",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.MaxKey.html",example:"new MaxKey()"},attributes:{}},MinKey:{help:{description:"The MinKey BSON Class",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.MinKey.html",example:"new MinKey()"},attributes:{}},ObjectId:{help:{description:"The ObjectId BSON Class",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.ObjectId.html",example:"new ObjectId(id: string|number [optional])"},attributes:{}},BSONSymbol:{help:{description:"The Symbol BSON Class. Deprecated since server version 1.6",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.BSONSymbol.html",example:'new BSONSymbol("abc")'},attributes:{}},Timestamp:{help:{description:"The Timestamp BSON Class",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.Timestamp.html",example:"new Timestamp(low: signed 32 bit number, high: signed 32 bit number)"},attributes:{}},Code:{help:{description:"The Code BSON Class",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.Code.html",example:'new Code("x", { x: 1 } [optional])'},attributes:{}},NumberDecimal:{help:{description:"A helper method that constructs a Decimal128 BSON Class from a string",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.Decimal128.html",example:'NumberDecimal("1.23423423")'}},Decimal128:{help:{description:"The Decimal128 BSON Class. Takes a Buffer as an argument.",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.Decimal128.html"},attributes:{}},NumberInt:{help:{description:"A helper method that constructs an Int32 BSON Class from a string",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.Int32.html",example:'NumberInt("123")'}},Int32:{help:{description:"The 32-bit Integer BSON Class",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.Int32.html",example:"new Int32(123)"},attributes:{}},Long:{help:{description:"The Long BSON Class",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.Long.html",example:"new Long(low: signed 32 bit number, high: signed 32 bit number)"},attributes:{}},Double:{help:{description:"The Double BSON Class.",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.Double.html",example:"new Double(123)"},attributes:{}},NumberLong:{help:{description:"A helper method that constructs a Long BSON Class from a string",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.Long.html",example:'NumberLong("123")'}},Date:{help:{description:"The Date Class"}},ISODate:{help:{description:"Helper method for creating dates using ISO"}},BinData:{help:{description:"A helper method that constructs a Binary BSON Class.",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.Binary.html",example:"BinData(subtype: number, base64string)"}},Binary:{help:{description:"The Binary BSON Class that takes in (Buffer, subtype: number) as arguments.",link:"https://mongodb.github.io/node-mongodb-native/Next/classes/BSON.Binary.html"},attributes:{SUBTYPE_BYTE_ARRAY:{description:"The byte array BSON type"},SUBTYPE_DEFAULT:{description:"The default BSON type"},SUBTYPE_FUNCTION:{description:"The function BSON type"},SUBTYPE_MD5:{description:"The MD5 BSON type"},SUBTYPE_USER_DEFINED:{description:"The user BSON type"},SUBTYPE_UUID:{description:"The UUID BSON type"},SUBTYPE_UUID_OLD:{description:"The Old UUID BSON type"}}},HexData:{help:{description:"Helper method to create BinData. Accepts subtype hex string",example:'HexData(0, "0123456789abcdef")'}},UUID:{help:{description:"Helper method to create BinData with subtype UUID. Accepts hex string (with optional dashes)",example:'UUID("01234567-89ab-cdef-0123-456789abcdef")'}},MD5:{help:{description:"Helper method to create BinData with subtype MD5. Accepts hex string",example:'MD5("0123456789abcdef0123456789abcdef")'}},bsonsize:{help:{description:"Helper method to calculate BSON object size",example:'bsonsize({ foo: "bar" })'}},Map:{help:{description:"BSON Map"}},Bulk:{help:{link:"https://mongodb.com/docs/manual/reference/method/Bulk",description:"Bulk operations builder used to construct a list of write operations to perform in bulk for a single collection. To instantiate the builder, use either the db.collection.initializeOrderedBulkOp() or the db.collection.initializeUnorderedBulkOp() method.",attributes:{insert:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.insert/",description:"Adds an insert to the bulk operation.",example:"db.insert(<document>)"},execute:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.execute/",description:"Executes the bulk operation.",example:"bulkOp.execute()"},find:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.find/",description:"Adds a find to the bulk operation.",example:"bulkOp.find(<filter>)"},getOperations:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.getOperations/",description:"Returns the batches executed by the bulk write.",example:"bulkOp.getOperations()"},tojson:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.tojson/",description:"Returns a JSON document that contains the number of operations and batches in the Bulk() object.",example:"bulkOp.tojson()"},toString:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.toString/",description:"Returns as a string a JSON document that contains the number of operations and batches in the Bulk() object.",example:"bulkOp.toString()"}}}},BulkFindOp:{help:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.find",description:"Bulk operations builder returned after Bulk.find()",attributes:{arrayFilters:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.find.arrayFilters/",description:"Adds an arrayFilter to the bulk operation.",example:"bulkOp.find(...).arrayFilters(<array of filters)"},hint:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.find.hint/",description:"Adds an hint to the bulk operation.",example:"bulkOp.find(...).hint(<hintd document>)"},collation:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.find.collation/",description:"Adds collation options to the bulk operation.",example:"bulkOp.find(...).collation(<collation doc>)"},remove:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.find.remove/",description:"Adds an remove to the bulk operation.",example:"bulkOp.find(...).remove()"},removeOne:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.find.removeOne/",description:"Adds an removeOne to the bulk operation.",example:"bulkOp.find(...).removeOne()"},delete:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.find.delete/",description:"Adds an delete to the bulk operation.",example:"bulkOp.find(...).delete()"},deleteOne:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.find.deleteOne/",description:"Adds an deleteOne to the bulk operation.",example:"bulkOp.find(...).deleteOne()"},replaceOne:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.find.replaceOne/",description:"Adds an replaceOne to the bulk operation.",example:"bulkOp.find(...).replaceOne(<document>)"},updateOne:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.find.updateOne/",description:"Adds an updateOne to the bulk operation.",example:"bulkOp.find(...).updateOne(<document>)"},update:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.find.update/",description:"Adds an update to the bulk operation.",example:"bulkOp.find(...).update(<document>)"},upsert:{link:"https://mongodb.com/docs/manual/reference/method/Bulk.find.upsert/",description:"Adds an upsert to the bulk operation updates for this find(...).",example:"bulkOp.find(...).upsert()"}}}},PlanCache:{help:{link:"https://mongodb.com/docs/manual/reference/method/js-plan-cache/",description:"An interface to access the query plan cache object and associated PlanCache methods for a collection.",attributes:{clear:{link:"https://mongodb.com/docs/manual/reference/method/PlanCache.clear",description:"Removes cached query plan(s) for a collection.",example:"db.coll.getPlanCache().clear()"},clearPlansByQuery:{link:"https://mongodb.com/docs/manual/reference/method/PlanCache.clearPlansByQuery",description:"Removes cached query plan(s) for a collection of the specified query shape.",example:"db.coll.getPlanCache().clearPlansByQuery(<query>, <projection?>, <sort?>)"},list:{link:"https://mongodb.com/docs/manual/reference/method/PlanCache.list",description:"Lists cached query plan(s) for a collection.",example:"db.coll.getPlanCache().list(<pipeline>)"},getPlansByQuery:{description:"Deprecated. Please use PlanCache.list instead"},listQueryShapes:{description:"Deprecated. Please use PlanCache.list instead"}}}},Document:{help:{link:"https://mongodb.com/docs/manual/core/document/",description:"A generic MongoDB document, without any methods.",attributes:{}}},KeyVault:{help:{link:"https://mongodb.com/docs/manual/core/security-client-side-encryption/",description:"The key vault object for the current MongoDB connection",attributes:{createKey:{description:"Creates a data encryption key for use with client-side field level encryption.",link:"https://mongodb.com/docs/manual/reference/method/KeyVault.createKey/#KeyVault.createKey"},deleteKey:{description:"Deletes the specified data encryption key from the key vault.",link:"https://mongodb.com/docs/manual/reference/method/KeyVault.deleteKey/#KeyVault.deleteKey"},getKey:{description:"Retreives the specified data encryption key from the key vault.",link:"https://mongodb.com/docs/manual/reference/method/KeyVault.getKey/#KeyVault.getKey"},getKeys:{description:"Retrieves all keys in the key vault.",link:"https://mongodb.com/docs/manual/reference/method/KeyVault.getKeys/#KeyVault.getKeys"},addKeyAlternateName:{description:"Associates a key alternative name to the specified data encryption key.",link:"https://mongodb.com/docs/manual/reference/method/KeyVault.addKeyAlternateName/#KeyVault.addKeyAlternateName"},removeKeyAlternateName:{description:"Removes a key alternative name from the specified data encryption key.",link:"https://mongodb.com/docs/manual/reference/method/KeyVault.removeKeyAlternateName/#KeyVault.removeKeyAlternateName"},getKeyByAltName:{description:"Retrieves keys with the specified key alternative name.",link:"https://mongodb.com/docs/manual/reference/method/KeyVault.getKeyByAltName/#KeyVault.getKeyByAltName"},rewrapManyDataKey:{description:"Re-wrap one, more, or all data keys with another KMS provider, or re-wrap using the same one.",link:"https://mongodb.com/docs/manual/reference/method/KeyVault.rewrapManyDataKey/#KeyVault.rewrapManyDataKey"},createDataKey:{description:"Alias of KeyVault.createKey()",link:"https://mongodb.com/docs/manual/reference/method/KeyVault.createKey/#KeyVault.createKey"},removeKeyAltName:{description:"Alias of KeyVault.removeKeyAlternateName()",link:"https://mongodb.com/docs/manual/reference/method/KeyVault.removeKeyAlternateName/#KeyVault.removeKeyAlternateName"},addKeyAltName:{description:"Alias of KeyVault.addKeyAlternateName()",link:"https://mongodb.com/docs/manual/reference/method/KeyVault.addKeyAlternateName/#KeyVault.addKeyAlternateName"}}}},ClientEncryption:{help:{link:"https://mongodb.com/docs/manual/core/security-client-side-encryption/",description:"The ClientEncryption object for the current database collection.",attributes:{encrypt:{link:"https://mongodb.com/docs/manual/reference/method/ClientEncryption.encrypt/#ClientEncryption.encrypt",description:"Encrypts the value using the specified encryptionKeyId and encryptionAlgorithm. encrypt supports explicit (manual) encryption of field values."},encryptExpression:{link:"https://mongodb.com/docs/manual/reference/method/ClientEncryption.encrypt/#ClientEncryption.encryptExpression",description:"Encrypts an MQL expression using the specified encryptionKeyId and encryptionAlgorithm."},decrypt:{link:"https://mongodb.com/docs/manual/reference/method/ClientEncryption.decrypt/#ClientEncryption.decrypt",description:"decrypts the encryptionValue if the current database connection was configured with access to the Key Management Service (KMS) and key vault used to encrypt encryptionValue."},createEncryptedCollection:{link:"https://mongodb.com/docs/manual/reference/method/ClientEncryption.createEncryptedCollection/#ClientEncryption.createEncryptedCollection",description:"Creates a new collection with a list of encrypted fields each with unique and auto-created data encryption keys (DEKs). This method should be invoked on a connection instantiated with queryable encryption options.",example:'db.getMongo().getClientEncryption().createEncryptedCollection( "dbName", "collName", { "provider": "<kmsProvider>", "createCollectionOptions": { "encryptedFields": { ... }, ...<otherOptions> } })'}}}},Streams:{help:{description:"Streams",attributes:{process:{description:"Allows a user to process streams of data in the shell interactively and quickly iterate building a stream processor as they go."},createStreamProcessor:{description:"Create a named stream processor."},getProcessor:{description:"Get a stream processor with specified name."},listStreamProcessors:{description:"Show a list of all the named stream processors."},listConnections:{description:"Show a list of all the named connections for this instance from the Connection Registry."},listWorkspaceDefaults:{description:"Show the default tier and maxTierSize for the stream processor workspace."}}}},StreamProcessor:{help:{description:"Stream processor",attributes:{start:{description:"Start a named stream processor."},stop:{description:"Stop a named stream processor."},drop:{description:"Drop a named stream processor."},sample:{description:"Return a sample of the results from a named stream processor."},stats:{description:"Return stats captured from a named stream processor."},modify:{description:"Modify a stream processor definition."}}}}}},"transport-browser":{"stitch-browser-transport":{"auth-error":"Error authenticating with Stitch."}},"transport-core":{"stitch-transport":{"not-implemented":"is not implemented in the Stitch SDK","agg-on-db":"Aggregations run on the database is not allowed via Stitch"}},"transport-server":{}}},71259:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WriteConcern=t.WRITE_CONCERN_KEYS=void 0,t.throwIfWriteConcernError=function(e){if("object"==typeof e&&null!=e){const t=n.MongoDBResponse.is(e)&&e.has("writeConcernError")?e.toObject():!n.MongoDBResponse.is(e)&&"writeConcernError"in e?e:null;if(null!=t)throw new r.MongoWriteConcernError(t)}};const n=o(72216),r=o(36997);t.WRITE_CONCERN_KEYS=["w","wtimeout","j","journal","fsync"];class i{constructor(e,t,o,n){null!=e&&(Number.isNaN(Number(e))?this.w=e:this.w=Number(e)),null!=t&&(this.wtimeoutMS=this.wtimeout=t),null!=o&&(this.journal=this.j=o),null!=n&&(this.journal=this.j=!!n)}static apply(e,t){const o={};return null!=t.w&&(o.w=t.w),null!=t.wtimeoutMS&&(o.wtimeout=t.wtimeoutMS),null!=t.journal&&(o.j=t.j),e.writeConcern=o,e}static fromOptions(e,t){if(null==e)return;let o;t=t??{},o="string"==typeof e||"number"==typeof e?{w:e}:e instanceof i?e:e.writeConcern;const n={...t instanceof i?t:t.writeConcern,...o},{w:r,wtimeout:s,j:a,fsync:c,journal:l,wtimeoutMS:d}=n;return null!=r||null!=s||null!=d||null!=a||null!=l||null!=c?new i(r,s??d,a??l,c):void 0}}t.WriteConcern=i},71260:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AWSSDKCredentialProvider=void 0;const n=o(15088),r=o(98517),i=o(36997);class s{constructor(e){e&&(this._provider=e)}static get awsSDK(){return s._awsSDK??=(0,r.getAwsCredentialProvider)(),s._awsSDK}get provider(){if("kModuleError"in s.awsSDK)throw s.awsSDK.kModuleError;if(this._provider)return this._provider;let{AWS_STS_REGIONAL_ENDPOINTS:e="",AWS_REGION:t=""}=n.env;e=e.toLowerCase(),t=t.toLowerCase();const o=0!==t.length&&0!==e.length,r=new Set(["ap-northeast-1","ap-south-1","ap-southeast-1","ap-southeast-2","aws-global","ca-central-1","eu-central-1","eu-north-1","eu-west-1","eu-west-2","eu-west-3","sa-east-1","us-east-1","us-east-2","us-west-1","us-west-2"]),i="regional"===e||"legacy"===e&&!r.has(t);return this._provider=o&&i?s.awsSDK.fromNodeProviderChain({clientConfig:{region:t}}):s.awsSDK.fromNodeProviderChain(),this._provider}async getCredentials(){try{const e=await this.provider();return{AccessKeyId:e.accessKeyId,SecretAccessKey:e.secretAccessKey,Token:e.sessionToken,Expiration:e.expiration}}catch(e){throw new i.MongoAWSError(e.message,{cause:e})}}}t.AWSSDKCredentialProvider=s},71789:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DbStatsOperation=void 0;const n=o(72216),r=o(41539),i=o(28947);class s extends r.CommandOperation{constructor(e,t){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=t}get commandName(){return"dbStats"}buildCommandDocument(e){const t={dbStats:!0};return null!=this.options.scale&&(t.scale=this.options.scale),t}}t.DbStatsOperation=s,(0,i.defineAspects)(s,[i.Aspect.READ_OPERATION])},72216:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteCursorResponse=t.ExplainedCursorResponse=t.CursorResponse=t.MongoDBResponse=void 0,t.isErrorResponse=c;const n=o(77953),r=o(36997),i=o(30306),s=o(65453),a={type:0,nameOffset:1,nameLength:2,offset:3,length:4};function c(e,t){for(let o=0;o<t.length;o++){const n=t[o];if(2===n[a.nameLength]){const t=n[a.nameOffset];if(111===e[t]&&107===e[t+1]){const t=n[a.offset],o=n[a.length];for(let n=t;n<t+o;n++)if(0!==e[n])return!1;return!0}}}return!0}class l extends s.OnDemandDocument{get(e,t,o){try{return super.get(e,t,o)}catch(e){throw new r.MongoUnexpectedServerResponseError(e.message,{cause:e})}}static is(e){return e instanceof l}static make(e){const t=(0,n.parseToElementsToArray)(e,0);return c(e,t)?new l(e,0,!1,t):new this(e,0,!1,t)}static{this.empty=new l(new Uint8Array([13,0,0,0,16,111,107,0,1,0,0,0,0]))}get isMaxTimeExpiredError(){if(0===this.ok&&this.code===r.MONGODB_ERROR_CODES.MaxTimeMSExpired)return!0;if(0===this.ok)return!1;if(this.get("writeConcernError",n.BSONType.object)?.getNumber("code")===r.MONGODB_ERROR_CODES.MaxTimeMSExpired)return!0;const e=this.get("writeErrors",n.BSONType.array);if(e?.size())for(let t=0;t<e.size();t++)if(e.get(t,n.BSONType.object)?.getNumber("code")===r.MONGODB_ERROR_CODES.MaxTimeMSExpired)return!0;return!1}get recoveryToken(){return this.get("recoveryToken",n.BSONType.object)?.toObject({promoteValues:!1,promoteLongs:!1,promoteBuffers:!1,validation:{utf8:!0}})??null}get atClusterTime(){return this.get("cursor",n.BSONType.object)?.get("atClusterTime",n.BSONType.timestamp)??this.get("atClusterTime",n.BSONType.timestamp)}get operationTime(){return this.get("operationTime",n.BSONType.timestamp)}get ok(){return this.getNumber("ok")?1:0}get $err(){return this.get("$err",n.BSONType.string)}get errmsg(){return this.get("errmsg",n.BSONType.string)}get code(){return this.getNumber("code")}get $clusterTime(){if(!("clusterTime"in this)){const e=this.get("$clusterTime",n.BSONType.object);if(null==e)return this.clusterTime=null,null;const t=e.get("clusterTime",n.BSONType.timestamp,!0),o=e.get("signature",n.BSONType.object)?.toObject();this.clusterTime={clusterTime:t,signature:o}}return this.clusterTime??null}toObject(e){const t={...(0,n.pluckBSONSerializeOptions)(e??{}),validation:(0,n.parseUtf8ValidationOption)(e)};return super.toObject(t)}}t.MongoDBResponse=l;class d extends l{constructor(){super(...arguments),this._batch=null,this.iterated=0,this._encryptedBatch=null}static get emptyGetMore(){return new d((0,n.serialize)({ok:1,cursor:{id:0n,nextBatch:[]}}))}static is(e){return e instanceof d||e===d.emptyGetMore}get cursor(){return this.get("cursor",n.BSONType.object,!0)}get id(){try{return n.Long.fromBigInt(this.cursor.get("id",n.BSONType.long,!0))}catch(e){throw new r.MongoUnexpectedServerResponseError(e.message,{cause:e})}}get ns(){const e=this.cursor.get("ns",n.BSONType.string);return null!=e?(0,i.ns)(e):null}get length(){return Math.max(this.batchSize-this.iterated,0)}get encryptedBatch(){if(null==this.encryptedResponse)return null;if(null!=this._encryptedBatch)return this._encryptedBatch;const e=this.encryptedResponse?.get("cursor",n.BSONType.object);if(e?.has("firstBatch"))this._encryptedBatch=e.get("firstBatch",n.BSONType.array,!0);else{if(!e?.has("nextBatch"))throw new r.MongoUnexpectedServerResponseError("Cursor document did not contain a batch");this._encryptedBatch=e.get("nextBatch",n.BSONType.array,!0)}return this._encryptedBatch}get batch(){if(null!=this._batch)return this._batch;const e=this.cursor;if(e.has("firstBatch"))this._batch=e.get("firstBatch",n.BSONType.array,!0);else{if(!e.has("nextBatch"))throw new r.MongoUnexpectedServerResponseError("Cursor document did not contain a batch");this._batch=e.get("nextBatch",n.BSONType.array,!0)}return this._batch}get batchSize(){return this.batch?.size()}get postBatchResumeToken(){return this.cursor.get("postBatchResumeToken",n.BSONType.object)?.toObject({promoteValues:!1,promoteLongs:!1,promoteBuffers:!1,validation:{utf8:!0}})??null}shift(e){if(this.iterated>=this.batchSize)return null;const t=this.batch.get(this.iterated,n.BSONType.object,!0)??null,o=this.encryptedBatch?.get(this.iterated,n.BSONType.object,!0)??null;if(this.iterated+=1,e?.raw)return t.toBytes();{const n=t.toObject(e);return o&&(0,i.decorateDecryptionResult)(n,o.toObject(e),!0),n}}clear(){this.iterated=this.batchSize}}t.CursorResponse=d,t.ExplainedCursorResponse=class extends d{constructor(){super(...arguments),this.isExplain=!0,this._length=1}get id(){return n.Long.fromBigInt(0n)}get batchSize(){return 0}get ns(){return null}get length(){return this._length}shift(e){return 0===this._length?null:(this._length-=1,this.toObject(e))}},t.ClientBulkWriteCursorResponse=class extends d{get insertedCount(){return this.get("nInserted",n.BSONType.int,!0)}get upsertedCount(){return this.get("nUpserted",n.BSONType.int,!0)}get matchedCount(){return this.get("nMatched",n.BSONType.int,!0)}get modifiedCount(){return this.get("nModified",n.BSONType.int,!0)}get deletedCount(){return this.get("nDeleted",n.BSONType.int,!0)}get writeConcernError(){return this.get("writeConcernError",n.BSONType.object,!1)}}},72361:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CancellationToken=t.TypedEventEmitter=void 0;const n=o(4580),r=o(60866),i=o(30306);class s extends n.EventEmitter{emitAndLog(e,...t){this.emit(e,...t),this.component&&this.mongoLogger?.debug(this.component,t[0])}emitAndLogHeartbeat(e,t,o,...n){if(this.emit(e,...n),this.component){const e={topologyId:t,serverConnectionId:o??null,...n[0]};this.mongoLogger?.debug(this.component,e)}}emitAndLogCommand(e,t,o,n,...i){if(e&&this.emit(t,...i),n){const e={databaseName:o,...i[0]};this.mongoLogger?.debug(r.MongoLoggableComponent.COMMAND,e)}}}t.TypedEventEmitter=s,t.CancellationToken=class extends s{constructor(...e){super(...e),this.on("error",i.noop)}}},72970:function(e,t,o){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r={...n(o(70533)).default};t.default=r},73533:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValidateCollectionOperation=void 0;const n=o(72216),r=o(36997),i=o(41539);class s extends i.CommandOperation{constructor(e,t,o){super(e.s.db,o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=o,this.collectionName=t}get commandName(){return"validate"}buildCommandDocument(e,t){return{validate:this.collectionName,...Object.fromEntries(Object.entries(this.options).filter((e=>"session"!==e[0])))}}handleOk(e){const t=super.handleOk(e);if(null!=t.result&&"string"!=typeof t.result)throw new r.MongoUnexpectedServerResponseError("Error with validation data");if(null!=t.result&&null!=t.result.match(/exception|corrupt/))throw new r.MongoUnexpectedServerResponseError(`Invalid collection ${this.collectionName}`);if(null!=t.valid&&!t.valid)throw new r.MongoUnexpectedServerResponseError(`Invalid collection ${this.collectionName}`);return e}}t.ValidateCollectionOperation=s},73738:(e,t,o)=>{var n=o(34110).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.uncompressibleCommands=t.Compressor=void 0,t.compress=async function(e,t){const o={};switch(e.agreedCompressor){case"snappy":return p??=g(),await p.compress(t);case"zstd":if(S(),"kModuleError"in m)throw m.kModuleError;return await m.compress(t,d);case"zlib":return e.zlibCompressionLevel&&(o.level=e.zlibCompressionLevel),await h(t,o);default:throw new a.MongoInvalidArgumentError(`Unknown compressor ${e.agreedCompressor} failed to compress`)}},t.decompress=f,t.compressCommand=async function(e,t){const o="none"!==t.agreedCompressor&&c.OpCompressedRequest.canCompress(e)?new c.OpCompressedRequest(e,{agreedCompressor:t.agreedCompressor??"none",zlibCompressionLevel:t.zlibCompressionLevel??0}):e,r=await o.toBin();return n.concat(r)},t.decompressResponse=async function(e){const t={length:e.readInt32LE(0),requestId:e.readInt32LE(4),responseTo:e.readInt32LE(8),opCode:e.readInt32LE(12)};if(t.opCode!==l.OP_COMPRESSED){const o=t.opCode===l.OP_MSG?c.OpMsgResponse:c.OpReply,n=e.subarray(E);return new o(e,t,n)}const o={...t,fromCompressed:!0,opCode:e.readInt32LE(E),length:e.readInt32LE(E+4)},n=e[E+8],r=e.slice(E+9),i=o.opCode===l.OP_MSG?c.OpMsgResponse:c.OpReply,s=await f(n,r);if(s.length!==o.length)throw new a.MongoDecompressionError("Message body and message header must be the same length");return new i(e,o,s)};const r=o(49042),i=o(34842),s=o(98517),a=o(36997),c=o(87535),l=o(60889);t.Compressor=Object.freeze({none:0,snappy:1,zlib:2,zstd:3}),t.uncompressibleCommands=new Set([i.LEGACY_HELLO_COMMAND,"saslStart","saslContinue","getnonce","authenticate","createUser","updateUser","copydbSaslStart","copydbgetnonce","copydb"]);const d=3,u=e=>new Promise(((t,o)=>{r.inflate(e,((e,n)=>{if(e)return o(e);t(n)}))})),h=(e,t)=>new Promise(((o,n)=>{r.deflate(e,t,((e,t)=>{if(e)return n(e);o(t)}))}));let m,p=null;function g(){if(null==p){const e=(0,s.getSnappy)();if("kModuleError"in e)throw e.kModuleError;p=e}return p}async function f(e,o){if(e!==t.Compressor.snappy&&e!==t.Compressor.zstd&&e!==t.Compressor.zlib&&e!==t.Compressor.none)throw new a.MongoDecompressionError(`Server sent message compressed using an unsupported compressor. (Received compressor ID ${e})`);switch(e){case t.Compressor.snappy:return p??=g(),await p.uncompress(o,{asBuffer:!0});case t.Compressor.zstd:if(S(),"kModuleError"in m)throw m.kModuleError;return await m.decompress(o);case t.Compressor.zlib:return await u(o);default:return o}}function S(){m||(m=(0,s.getZstdLibrary)())}const E=16},74891:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadPreference=t.ReadPreferenceMode=void 0;const n=o(36997);t.ReadPreferenceMode=Object.freeze({primary:"primary",primaryPreferred:"primaryPreferred",secondary:"secondary",secondaryPreferred:"secondaryPreferred",nearest:"nearest"});class r{static{this.PRIMARY=t.ReadPreferenceMode.primary}static{this.PRIMARY_PREFERRED=t.ReadPreferenceMode.primaryPreferred}static{this.SECONDARY=t.ReadPreferenceMode.secondary}static{this.SECONDARY_PREFERRED=t.ReadPreferenceMode.secondaryPreferred}static{this.NEAREST=t.ReadPreferenceMode.nearest}static{this.primary=new r(t.ReadPreferenceMode.primary)}static{this.primaryPreferred=new r(t.ReadPreferenceMode.primaryPreferred)}static{this.secondary=new r(t.ReadPreferenceMode.secondary)}static{this.secondaryPreferred=new r(t.ReadPreferenceMode.secondaryPreferred)}static{this.nearest=new r(t.ReadPreferenceMode.nearest)}constructor(e,t,o){if(!r.isValid(e))throw new n.MongoInvalidArgumentError(`Invalid read preference mode ${JSON.stringify(e)}`);if(null!=o||"object"!=typeof t||Array.isArray(t)){if(t&&!Array.isArray(t))throw new n.MongoInvalidArgumentError("ReadPreference tags must be an array")}else o=t,t=void 0;if(this.mode=e,this.tags=t,this.hedge=o?.hedge,this.maxStalenessSeconds=void 0,null!=(o=o??{}).maxStalenessSeconds){if(o.maxStalenessSeconds<=0)throw new n.MongoInvalidArgumentError("maxStalenessSeconds must be a positive integer");this.maxStalenessSeconds=o.maxStalenessSeconds}if(this.mode===r.PRIMARY){if(this.tags&&Array.isArray(this.tags)&&this.tags.length>0)throw new n.MongoInvalidArgumentError("Primary read preference cannot be combined with tags");if(this.maxStalenessSeconds)throw new n.MongoInvalidArgumentError("Primary read preference cannot be combined with maxStalenessSeconds");if(this.hedge)throw new n.MongoInvalidArgumentError("Primary read preference cannot be combined with hedge")}}get preference(){return this.mode}static fromString(e){return new r(e)}static fromOptions(e){if(!e)return;const t=e.readPreference??e.session?.transaction.options.readPreference,o=e.readPreferenceTags;if(null!=t){if("string"==typeof t)return new r(t,o,{maxStalenessSeconds:e.maxStalenessSeconds,hedge:e.hedge});if(!(t instanceof r)&&"object"==typeof t){const n=t.mode||t.preference;if(n&&"string"==typeof n)return new r(n,t.tags??o,{maxStalenessSeconds:t.maxStalenessSeconds,hedge:e.hedge})}return o&&(t.tags=o),t}}static translate(e){if(null==e.readPreference)return e;const t=e.readPreference;if("string"==typeof t)e.readPreference=new r(t);else if(!t||t instanceof r||"object"!=typeof t){if(!(t instanceof r))throw new n.MongoInvalidArgumentError(`Invalid read preference: ${t}`)}else{const o=t.mode||t.preference;o&&"string"==typeof o&&(e.readPreference=new r(o,t.tags,{maxStalenessSeconds:t.maxStalenessSeconds}))}return e}static isValid(e){return new Set([r.PRIMARY,r.PRIMARY_PREFERRED,r.SECONDARY,r.SECONDARY_PREFERRED,r.NEAREST,null]).has(e)}isValid(e){return r.isValid("string"==typeof e?e:this.mode)}secondaryOk(){return new Set([r.PRIMARY_PREFERRED,r.SECONDARY,r.SECONDARY_PREFERRED,r.NEAREST]).has(this.mode)}equals(e){return e.mode===this.mode}toJSON(){const e={mode:this.mode};return Array.isArray(this.tags)&&(e.tags=this.tags),this.maxStalenessSeconds&&(e.maxStalenessSeconds=this.maxStalenessSeconds),this.hedge&&(e.hedge=this.hedge),e}}t.ReadPreference=r},75878:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RenameOperation=void 0;const n=o(72216),r=o(53975),i=o(30306),s=o(41539),a=o(28947);class c extends s.CommandOperation{constructor(e,t,o){super(e,o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.collection=e,this.newName=t,this.options=o,this.ns=new i.MongoDBNamespace("admin","$cmd")}get commandName(){return"renameCollection"}buildCommandDocument(e,t){return{renameCollection:this.collection.namespace,to:this.collection.s.namespace.withCollection(this.newName).toString(),dropTarget:"boolean"==typeof this.options.dropTarget&&this.options.dropTarget}}handleOk(e){return new r.Collection(this.collection.db,this.newName,this.collection.s.options)}}t.RenameOperation=c,(0,a.defineAspects)(c,[a.Aspect.WRITE_OPERATION])},76203:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteCursor=void 0;const n=o(78817),r=o(39131),i=o(30306),s=o(40927);class a extends s.AbstractCursor{constructor(e,t,o={}){super(e,new i.MongoDBNamespace("admin","$cmd"),o),this.commandBuilder=t,this.clientBulkWriteOptions=o}get response(){return this.cursorResponse?this.cursorResponse:null}get operations(){return this.commandBuilder.lastOperations}clone(){const e=(0,i.mergeOptions)({},this.clientBulkWriteOptions);return delete e.session,new a(this.client,this.commandBuilder,{...e})}async _initialize(e){const t=new n.ClientBulkWriteOperation(this.commandBuilder,{...this.clientBulkWriteOptions,...this.cursorOptions,session:e}),o=await(0,r.executeOperation)(this.client,t,this.timeoutContext);return this.cursorResponse=o,{server:t.server,session:e,response:o}}}t.ClientBulkWriteCursor=a},77953:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toUTF8=t.getBigInt64LE=t.getFloat64LE=t.getInt32LE=t.UUID=t.Timestamp=t.serialize=t.ObjectId=t.NumberUtils=t.MinKey=t.MaxKey=t.Long=t.Int32=t.EJSON=t.Double=t.deserialize=t.Decimal128=t.DBRef=t.Code=t.calculateObjectSize=t.BSONType=t.BSONSymbol=t.BSONRegExp=t.BSONError=t.BSON=t.Binary=void 0,t.parseToElementsToArray=function(e,t){const o=n.BSON.onDemand.parseToElements(e,t);return Array.isArray(o)?o:[...o]},t.pluckBSONSerializeOptions=function(e){const{fieldsAsRaw:t,useBigInt64:o,promoteValues:n,promoteBuffers:r,promoteLongs:i,serializeFunctions:s,ignoreUndefined:a,bsonRegExp:c,raw:l,enableUtf8Validation:d}=e;return{fieldsAsRaw:t,useBigInt64:o,promoteValues:n,promoteBuffers:r,promoteLongs:i,serializeFunctions:s,ignoreUndefined:a,bsonRegExp:c,raw:l,enableUtf8Validation:d}},t.resolveBSONOptions=function(e,t){const o=t?.bsonOptions;return{raw:e?.raw??o?.raw??!1,useBigInt64:e?.useBigInt64??o?.useBigInt64??!1,promoteLongs:e?.promoteLongs??o?.promoteLongs??!0,promoteValues:e?.promoteValues??o?.promoteValues??!0,promoteBuffers:e?.promoteBuffers??o?.promoteBuffers??!1,ignoreUndefined:e?.ignoreUndefined??o?.ignoreUndefined??!1,bsonRegExp:e?.bsonRegExp??o?.bsonRegExp??!1,serializeFunctions:e?.serializeFunctions??o?.serializeFunctions??!1,fieldsAsRaw:e?.fieldsAsRaw??o?.fieldsAsRaw??{},enableUtf8Validation:e?.enableUtf8Validation??o?.enableUtf8Validation??!0}},t.parseUtf8ValidationOption=function(e){const t=e?.enableUtf8Validation;return!1===t?{utf8:!1}:{utf8:{writeErrors:!1}}};const n=o(13353);var r=o(13353);Object.defineProperty(t,"Binary",{enumerable:!0,get:function(){return r.Binary}}),Object.defineProperty(t,"BSON",{enumerable:!0,get:function(){return r.BSON}}),Object.defineProperty(t,"BSONError",{enumerable:!0,get:function(){return r.BSONError}}),Object.defineProperty(t,"BSONRegExp",{enumerable:!0,get:function(){return r.BSONRegExp}}),Object.defineProperty(t,"BSONSymbol",{enumerable:!0,get:function(){return r.BSONSymbol}}),Object.defineProperty(t,"BSONType",{enumerable:!0,get:function(){return r.BSONType}}),Object.defineProperty(t,"calculateObjectSize",{enumerable:!0,get:function(){return r.calculateObjectSize}}),Object.defineProperty(t,"Code",{enumerable:!0,get:function(){return r.Code}}),Object.defineProperty(t,"DBRef",{enumerable:!0,get:function(){return r.DBRef}}),Object.defineProperty(t,"Decimal128",{enumerable:!0,get:function(){return r.Decimal128}}),Object.defineProperty(t,"deserialize",{enumerable:!0,get:function(){return r.deserialize}}),Object.defineProperty(t,"Double",{enumerable:!0,get:function(){return r.Double}}),Object.defineProperty(t,"EJSON",{enumerable:!0,get:function(){return r.EJSON}}),Object.defineProperty(t,"Int32",{enumerable:!0,get:function(){return r.Int32}}),Object.defineProperty(t,"Long",{enumerable:!0,get:function(){return r.Long}}),Object.defineProperty(t,"MaxKey",{enumerable:!0,get:function(){return r.MaxKey}}),Object.defineProperty(t,"MinKey",{enumerable:!0,get:function(){return r.MinKey}}),Object.defineProperty(t,"NumberUtils",{enumerable:!0,get:function(){return r.NumberUtils}}),Object.defineProperty(t,"ObjectId",{enumerable:!0,get:function(){return r.ObjectId}}),Object.defineProperty(t,"serialize",{enumerable:!0,get:function(){return r.serialize}}),Object.defineProperty(t,"Timestamp",{enumerable:!0,get:function(){return r.Timestamp}}),Object.defineProperty(t,"UUID",{enumerable:!0,get:function(){return r.UUID}}),t.getInt32LE=n.BSON.onDemand.NumberUtils.getInt32LE,t.getFloat64LE=n.BSON.onDemand.NumberUtils.getFloat64LE,t.getBigInt64LE=n.BSON.onDemand.NumberUtils.getBigInt64LE,t.toUTF8=n.BSON.onDemand.ByteUtils.toUTF8},78817:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ClientBulkWriteOperation=void 0;const n=o(72216),r=o(30306),i=o(41539),s=o(28947);class a extends i.CommandOperation{get commandName(){return"bulkWrite"}constructor(e,t){super(void 0,t),this.SERVER_COMMAND_RESPONSE_TYPE=n.ClientBulkWriteCursorResponse,this.commandBuilder=e,this.options=t,this.ns=new r.MongoDBNamespace("admin","$cmd")}resetBatch(){return this.commandBuilder.resetBatch()}get canRetryWrite(){return this.commandBuilder.isBatchRetryable}handleOk(e){return e}buildCommandDocument(e,t){const o=this.commandBuilder.buildBatch(e.description.maxMessageSizeBytes,e.description.maxWriteBatchSize,e.description.maxBsonObjectSize);return this.canRetryWrite||(this.options.willRetryWrite=!1),o}}t.ClientBulkWriteOperation=a,(0,s.defineAspects)(a,[s.Aspect.WRITE_OPERATION,s.Aspect.SKIP_COLLATION,s.Aspect.CURSOR_CREATING,s.Aspect.RETRYABLE,s.Aspect.COMMAND_BATCHING,s.Aspect.SUPPORTS_RAW_DATA])},78948:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionPoolClearedEvent=t.ConnectionCheckedInEvent=t.ConnectionCheckedOutEvent=t.ConnectionCheckOutFailedEvent=t.ConnectionCheckOutStartedEvent=t.ConnectionClosedEvent=t.ConnectionReadyEvent=t.ConnectionCreatedEvent=t.ConnectionPoolClosedEvent=t.ConnectionPoolReadyEvent=t.ConnectionPoolCreatedEvent=t.ConnectionPoolMonitoringEvent=void 0;const n=o(34842),r=o(30306);class i{constructor(e){this.time=new Date,this.address=e.address}}t.ConnectionPoolMonitoringEvent=i,t.ConnectionPoolCreatedEvent=class extends i{constructor(e){super(e),this.name=n.CONNECTION_POOL_CREATED;const{maxConnecting:t,maxPoolSize:o,minPoolSize:r,maxIdleTimeMS:i,waitQueueTimeoutMS:s}=e.options;this.options={maxConnecting:t,maxPoolSize:o,minPoolSize:r,maxIdleTimeMS:i,waitQueueTimeoutMS:s}}},t.ConnectionPoolReadyEvent=class extends i{constructor(e){super(e),this.name=n.CONNECTION_POOL_READY}},t.ConnectionPoolClosedEvent=class extends i{constructor(e){super(e),this.name=n.CONNECTION_POOL_CLOSED}},t.ConnectionCreatedEvent=class extends i{constructor(e,t){super(e),this.name=n.CONNECTION_CREATED,this.connectionId=t.id}},t.ConnectionReadyEvent=class extends i{constructor(e,t,o){super(e),this.name=n.CONNECTION_READY,this.durationMS=(0,r.processTimeMS)()-o,this.connectionId=t.id}},t.ConnectionClosedEvent=class extends i{constructor(e,t,o,r){super(e),this.name=n.CONNECTION_CLOSED,this.connectionId=t.id,this.reason=o,this.serviceId=t.serviceId,this.error=r??null}},t.ConnectionCheckOutStartedEvent=class extends i{constructor(e){super(e),this.name=n.CONNECTION_CHECK_OUT_STARTED}},t.ConnectionCheckOutFailedEvent=class extends i{constructor(e,t,o,i){super(e),this.name=n.CONNECTION_CHECK_OUT_FAILED,this.durationMS=(0,r.processTimeMS)()-o,this.reason=t,this.error=i}},t.ConnectionCheckedOutEvent=class extends i{constructor(e,t,o){super(e),this.name=n.CONNECTION_CHECKED_OUT,this.durationMS=(0,r.processTimeMS)()-o,this.connectionId=t.id}},t.ConnectionCheckedInEvent=class extends i{constructor(e,t){super(e),this.name=n.CONNECTION_CHECKED_IN,this.connectionId=t.id}},t.ConnectionPoolClearedEvent=class extends i{constructor(e,t={}){super(e),this.name=n.CONNECTION_POOL_CLEARED,this.serviceId=t.serviceId,this.interruptInUseConnections=t.interruptInUseConnections}}},79573:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TopologyDescription=void 0;const n=o(77953),r=o(60889),i=o(36997),s=o(30306),a=o(90648),c=o(32583),l=r.MIN_SUPPORTED_SERVER_VERSION,d=r.MAX_SUPPORTED_SERVER_VERSION,u=r.MIN_SUPPORTED_WIRE_VERSION,h=r.MAX_SUPPORTED_WIRE_VERSION,m=new Set([a.ServerType.Mongos,a.ServerType.Unknown]),p=new Set([a.ServerType.Mongos,a.ServerType.Standalone]),g=new Set([a.ServerType.RSSecondary,a.ServerType.RSArbiter,a.ServerType.RSOther]);class f{constructor(e,t=null,o=null,n=null,r=null,i=null,s=null){s=s??{},this.type=e??a.TopologyType.Unknown,this.servers=t??new Map,this.stale=!1,this.compatible=!0,this.heartbeatFrequencyMS=s.heartbeatFrequencyMS??0,this.localThresholdMS=s.localThresholdMS??15,this.setName=o??null,this.maxElectionId=r??null,this.maxSetVersion=n??null,this.commonWireVersion=i??0;for(const e of this.servers.values())if(e.type!==a.ServerType.Unknown&&e.type!==a.ServerType.LoadBalancer&&(e.minWireVersion>h&&(this.compatible=!1,this.compatibilityError=`Server at ${e.address} requires wire version ${e.minWireVersion}, but this version of the driver only supports up to ${h} (MongoDB ${d})`),e.maxWireVersion<u)){this.compatible=!1,this.compatibilityError=`Server at ${e.address} reports wire version ${e.maxWireVersion}, but this version of the driver requires at least ${u} (MongoDB ${l}).`;break}this.logicalSessionTimeoutMinutes=null;for(const[,e]of this.servers)if(e.isReadable){if(null==e.logicalSessionTimeoutMinutes){this.logicalSessionTimeoutMinutes=null;break}if(null==this.logicalSessionTimeoutMinutes){this.logicalSessionTimeoutMinutes=e.logicalSessionTimeoutMinutes;continue}this.logicalSessionTimeoutMinutes=Math.min(this.logicalSessionTimeoutMinutes,e.logicalSessionTimeoutMinutes)}}updateFromSrvPollingEvent(e,t=0){const o=e.hostnames(),n=new Set(this.servers.keys()),r=new Set(o),i=new Set;for(const e of n)r.delete(e),o.has(e)||i.add(e);if(0===r.size&&0===i.size)return this;const a=new Map(this.servers);for(const e of i)a.delete(e);if(r.size>0)if(0===t)for(const e of r)a.set(e,new c.ServerDescription(e));else if(a.size<t){const e=(0,s.shuffle)(r,t-a.size);for(const t of e)a.set(t,new c.ServerDescription(t))}return new f(this.type,a,this.setName,this.maxSetVersion,this.maxElectionId,this.commonWireVersion,{heartbeatFrequencyMS:this.heartbeatFrequencyMS,localThresholdMS:this.localThresholdMS})}update(e){const t=e.address;let{type:o,setName:n,maxSetVersion:r,maxElectionId:s,commonWireVersion:l}=this;const d=e.type,u=new Map(this.servers);if(0!==e.maxWireVersion&&(l=0===l?e.maxWireVersion:Math.min(l,e.maxWireVersion)),"string"==typeof e.setName&&"string"==typeof n&&e.setName!==n&&(o===a.TopologyType.Single?e=new c.ServerDescription(t):u.delete(t)),u.set(t,e),o===a.TopologyType.Single)return new f(a.TopologyType.Single,u,n,r,s,l,{heartbeatFrequencyMS:this.heartbeatFrequencyMS,localThresholdMS:this.localThresholdMS});if(o===a.TopologyType.Unknown&&(d===a.ServerType.Standalone&&1!==this.servers.size?u.delete(t):o=function(e){switch(e){case a.ServerType.Standalone:return a.TopologyType.Single;case a.ServerType.Mongos:return a.TopologyType.Sharded;case a.ServerType.RSPrimary:return a.TopologyType.ReplicaSetWithPrimary;case a.ServerType.RSOther:case a.ServerType.RSSecondary:return a.TopologyType.ReplicaSetNoPrimary;default:return a.TopologyType.Unknown}}(d)),o===a.TopologyType.Sharded&&(m.has(d)||u.delete(t)),o===a.TopologyType.ReplicaSetNoPrimary)if(p.has(d)&&u.delete(t),d===a.ServerType.RSPrimary){const t=S(u,e,n,r,s);o=t[0],n=t[1],r=t[2],s=t[3]}else if(g.has(d)){const t=function(e,t,o=null){const n=a.TopologyType.ReplicaSetNoPrimary;return(o=o??t.setName)!==t.setName?(e.delete(t.address),[n,o]):(t.allHosts.forEach((t=>{e.has(t)||e.set(t,new c.ServerDescription(t))})),t.me&&t.address!==t.me&&e.delete(t.address),[n,o])}(u,e,n);o=t[0],n=t[1]}if(o===a.TopologyType.ReplicaSetWithPrimary)if(p.has(d))u.delete(t),o=E(u);else if(d===a.ServerType.RSPrimary){const t=S(u,e,n,r,s);o=t[0],n=t[1],r=t[2],s=t[3]}else o=g.has(d)?function(e,t,o=null){if(null==o)throw new i.MongoRuntimeError('Argument "setName" is required if connected to a replica set');return(o!==t.setName||t.me&&t.address!==t.me)&&e.delete(t.address),E(e)}(u,e,n):E(u);return new f(o,u,n,r,s,l,{heartbeatFrequencyMS:this.heartbeatFrequencyMS,localThresholdMS:this.localThresholdMS})}get error(){const e=Array.from(this.servers.values()).filter((e=>e.error));return e.length>0?e[0].error:null}get hasKnownServers(){return Array.from(this.servers.values()).some((e=>e.type!==a.ServerType.Unknown))}get hasDataBearingServers(){return Array.from(this.servers.values()).some((e=>e.isDataBearing))}hasServer(e){return this.servers.has(e)}toJSON(){return n.EJSON.serialize(this)}}function S(e,t,o=null,n=null,r=null){const l=(e,t,o)=>`primary marked stale due to electionId/setVersion mismatch: server setVersion: ${e.setVersion}, server electionId: ${e.electionId}, topology setVersion: ${t}, topology electionId: ${o}`;if((o=o||t.setName)!==t.setName)return e.delete(t.address),[E(e),o,n,r];if(t.maxWireVersion>=17){const a=(0,s.compareObjectId)(r,t.electionId),d=0===a,u=-1===a,h=(n??-1)<=(t.setVersion??-1);if(!(u||d&&h))return e.set(t.address,new c.ServerDescription(t.address,void 0,{error:new i.MongoStalePrimaryError(l(t,n,r))})),[E(e),o,n,r];r=t.electionId,n=t.setVersion}else{const a=t.electionId?t.electionId:null;if(t.setVersion&&a){if(n&&r&&(n>t.setVersion||(0,s.compareObjectId)(r,a)>0))return e.set(t.address,new c.ServerDescription(t.address,void 0,{error:new i.MongoStalePrimaryError(l(t,n,r))})),[E(e),o,n,r];r=t.electionId}null!=t.setVersion&&(null==n||t.setVersion>n)&&(n=t.setVersion)}for(const[o,n]of e)if(n.type===a.ServerType.RSPrimary&&n.address!==t.address){e.set(o,new c.ServerDescription(n.address,void 0,{error:new i.MongoStalePrimaryError("primary marked stale due to discovery of newer primary")}));break}t.allHosts.forEach((t=>{e.has(t)||e.set(t,new c.ServerDescription(t))}));const d=Array.from(e.keys()),u=t.allHosts;return d.filter((e=>-1===u.indexOf(e))).forEach((t=>{e.delete(t)})),[E(e),o,n,r]}function E(e){for(const t of e.values())if(t.type===a.ServerType.RSPrimary)return a.TopologyType.ReplicaSetWithPrimary;return a.TopologyType.ReplicaSetNoPrimary}t.TopologyDescription=f},80351:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getReadPreference=function(e){let t=e?.readPreference??r.ReadPreference.primary;if("string"==typeof t&&(t=r.ReadPreference.fromString(t)),!(t instanceof r.ReadPreference))throw new n.MongoInvalidArgumentError('Option "readPreference" must be a ReadPreference instance');return t},t.isSharded=function(e){return null!=e&&(!(!e.description||e.description.type!==i.ServerType.Mongos)||!!(e.description&&e.description instanceof s.TopologyDescription)&&Array.from(e.description.servers.values()).some((e=>e.type===i.ServerType.Mongos)))};const n=o(36997),r=o(74891),i=o(90648),s=o(79573)},80529:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OrderedBulkOperation=void 0;const n=o(77953),r=o(36997),i=o(82403);class s extends i.BulkOperationBase{constructor(e,t){super(e,t,!0)}addToOperationsList(e,t){const o=n.calculateObjectSize(t,{checkKeys:!1,ignoreUndefined:!1});if(o>=this.s.maxBsonObjectSize)throw new r.MongoInvalidArgumentError(`Document is larger than the maximum size ${this.s.maxBsonObjectSize}`);null==this.s.currentBatch&&(this.s.currentBatch=new i.Batch(e,this.s.currentIndex));const s=this.s.maxKeySize;if((this.s.currentBatchSize+1>=this.s.maxWriteBatchSize||this.s.currentBatchSize>0&&this.s.currentBatchSizeBytes+s+o>=this.s.maxBatchSizeBytes||this.s.currentBatch.batchType!==e)&&(this.s.batches.push(this.s.currentBatch),this.s.currentBatch=new i.Batch(e,this.s.currentIndex),this.s.currentBatchSize=0,this.s.currentBatchSizeBytes=0),e===i.BatchType.INSERT&&this.s.bulkResult.insertedIds.push({index:this.s.currentIndex,_id:t._id}),Array.isArray(t))throw new r.MongoInvalidArgumentError("Operation passed in cannot be an Array");return this.s.currentBatch.originalIndexes.push(this.s.currentIndex),this.s.currentBatch.operations.push(t),this.s.currentBatchSize+=1,this.s.currentBatchSizeBytes+=s+o,this.s.currentIndex+=1,this}}t.OrderedBulkOperation=s},80568:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Admin=void 0;const n=o(77953),r=o(39131),i=o(20693),s=o(85052),a=o(9405),c=o(73533),l=o(30306);t.Admin=class{constructor(e){this.s={db:e}}async command(e,t){return await(0,r.executeOperation)(this.s.db.client,new a.RunCommandOperation(new l.MongoDBNamespace("admin"),e,{...(0,n.resolveBSONOptions)(t),session:t?.session,readPreference:t?.readPreference,timeoutMS:t?.timeoutMS??this.s.db.timeoutMS}))}async buildInfo(e){return await this.command({buildinfo:1},e)}async serverInfo(e){return await this.command({buildinfo:1},e)}async serverStatus(e){return await this.command({serverStatus:1},e)}async ping(e){return await this.command({ping:1},e)}async removeUser(e,t){return await(0,r.executeOperation)(this.s.db.client,new s.RemoveUserOperation(this.s.db,e,{dbName:"admin",...t}))}async validateCollection(e,t={}){return await(0,r.executeOperation)(this.s.db.client,new c.ValidateCollectionOperation(this,e,t))}async listDatabases(e){return await(0,r.executeOperation)(this.s.db.client,new i.ListDatabasesOperation(this.s.db,{timeoutMS:this.s.db.timeoutMS,...e}))}async replSetGetStatus(e){return await this.command({replSetGetStatus:1},e)}}},82403:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BulkOperationBase=t.FindOperators=t.MongoBulkWriteError=t.WriteError=t.WriteConcernError=t.BulkWriteResult=t.Batch=t.BatchType=void 0,t.mergeBatchResults=g;const n=o(77953),r=o(36997),i=o(27827),s=o(39131),a=o(11337),c=o(82521),l=o(33628),d=o(30306),u=o(71259);t.BatchType=Object.freeze({INSERT:1,UPDATE:2,DELETE:3}),t.Batch=class{constructor(e,t){this.originalZeroIndex=t,this.currentIndex=0,this.originalIndexes=[],this.batchType=e,this.operations=[],this.size=0,this.sizeBytes=0}};class h{static generateIdMap(e){const t={};for(const o of e)t[o.index]=o._id;return t}constructor(e,t){this.result=e,this.insertedCount=this.result.nInserted??0,this.matchedCount=this.result.nMatched??0,this.modifiedCount=this.result.nModified??0,this.deletedCount=this.result.nRemoved??0,this.upsertedCount=this.result.upserted.length??0,this.upsertedIds=h.generateIdMap(this.result.upserted),this.insertedIds=h.generateIdMap(this.getSuccessfullyInsertedIds(e,t)),Object.defineProperty(this,"result",{value:this.result,enumerable:!1})}get ok(){return this.result.ok}getSuccessfullyInsertedIds(e,t){return 0===e.writeErrors.length?e.insertedIds:t?e.insertedIds.slice(0,e.writeErrors[0].index):e.insertedIds.filter((({index:t})=>!e.writeErrors.some((e=>t===e.index))))}getUpsertedIdAt(e){return this.result.upserted[e]}getRawResponse(){return this.result}hasWriteErrors(){return this.result.writeErrors.length>0}getWriteErrorCount(){return this.result.writeErrors.length}getWriteErrorAt(e){return e<this.result.writeErrors.length?this.result.writeErrors[e]:void 0}getWriteErrors(){return this.result.writeErrors}getWriteConcernError(){if(0!==this.result.writeConcernErrors.length){if(1===this.result.writeConcernErrors.length)return this.result.writeConcernErrors[0];{let e="";for(let t=0;t<this.result.writeConcernErrors.length;t++)e+=this.result.writeConcernErrors[t].errmsg,0===t&&(e+=" and ");return new m({errmsg:e,code:r.MONGODB_ERROR_CODES.WriteConcernTimeout})}}}toString(){return`BulkWriteResult(${n.EJSON.stringify(this.result)})`}isOk(){return 1===this.result.ok}}t.BulkWriteResult=h;class m{constructor(e){this.serverError=e}get code(){return this.serverError.code}get errmsg(){return this.serverError.errmsg}get errInfo(){return this.serverError.errInfo}toJSON(){return this.serverError}toString(){return`WriteConcernError(${this.errmsg})`}}t.WriteConcernError=m;class p{constructor(e){this.err=e}get code(){return this.err.code}get index(){return this.err.index}get errmsg(){return this.err.errmsg}get errInfo(){return this.err.errInfo}getOperation(){return this.err.op}toJSON(){return{code:this.err.code,index:this.err.index,errmsg:this.err.errmsg,op:this.err.op}}toString(){return`WriteError(${JSON.stringify(this.toJSON())})`}}function g(e,t,o,n){if(o?n=o:n&&n.result&&(n=n.result),null==n)return;if(0===n.ok&&1===t.ok){t.ok=0;const o={index:0,code:n.code||0,errmsg:n.message,errInfo:n.errInfo,op:e.operations[0]};return void t.writeErrors.push(new p(o))}if(0===n.ok&&0===t.ok)return;y(e)&&n.n&&(t.nInserted=t.nInserted+n.n),O(e)&&n.n&&(t.nRemoved=t.nRemoved+n.n);let r=0;if(Array.isArray(n.upserted)){r=n.upserted.length;for(let o=0;o<n.upserted.length;o++)t.upserted.push({index:n.upserted[o].index+e.originalZeroIndex,_id:n.upserted[o]._id})}else n.upserted&&(r=1,t.upserted.push({index:e.originalZeroIndex,_id:n.upserted}));if(b(e)&&n.n){const e=n.nModified;t.nUpserted=t.nUpserted+r,t.nMatched=t.nMatched+(n.n-r),t.nModified="number"==typeof e?t.nModified+e:0}if(Array.isArray(n.writeErrors))for(let o=0;o<n.writeErrors.length;o++){const r={index:e.originalIndexes[n.writeErrors[o].index],code:n.writeErrors[o].code,errmsg:n.writeErrors[o].errmsg,errInfo:n.writeErrors[o].errInfo,op:e.operations[n.writeErrors[o].index]};t.writeErrors.push(new p(r))}n.writeConcernError&&t.writeConcernErrors.push(new m(n.writeConcernError))}async function f(e,t){if(0===e.s.batches.length)return new h(e.s.bulkResult,e.isOrdered);for(const o of e.s.batches){const n=(0,d.resolveOptions)(e,{...t,ordered:e.isOrdered});!0!==n.bypassDocumentValidation&&delete n.bypassDocumentValidation,!0===e.s.bypassDocumentValidation&&(n.bypassDocumentValidation=!0),!1===e.s.checkKeys&&(n.checkKeys=!1),e.retryWrites&&(b(o)&&(e.retryWrites=e.retryWrites&&!o.operations.some((e=>e.multi))),O(o)&&(e.retryWrites=e.retryWrites&&!o.operations.some((e=>0===e.limit))));const l=y(o)?new a.InsertOperation(e.s.namespace,o.operations,n):b(o)?new c.UpdateOperation(e.s.namespace,o.operations,n):O(o)?new i.DeleteOperation(e.s.namespace,o.operations,n):null;if(null==l)throw new r.MongoRuntimeError(`Unknown batchType: ${o.batchType}`);let u,m=null;try{u=await(0,s.executeOperation)(e.s.collection.client,l,n.timeoutContext)}catch(e){m=e}if(null!=m){if(m instanceof r.MongoWriteConcernError){g(o,e.s.bulkResult,m,u);const t=new h(e.s.bulkResult,e.isOrdered);throw new S({message:m.result.writeConcernError.errmsg,code:m.result.writeConcernError.code},t)}throw new S(m,new h(e.s.bulkResult,e.isOrdered))}g(o,e.s.bulkResult,m,u);const p=new h(e.s.bulkResult,e.isOrdered);e.handleWriteError(p)}e.s.batches.length=0;const o=new h(e.s.bulkResult,e.isOrdered);return e.handleWriteError(o),o}t.WriteError=p;class S extends r.MongoServerError{constructor(e,t){super(e),this.writeErrors=[],e instanceof m?this.err=e:e instanceof Error||(this.message=e.message,this.code=e.code,this.writeErrors=e.writeErrors??[]),this.result=t,Object.assign(this,e)}get name(){return"MongoBulkWriteError"}get insertedCount(){return this.result.insertedCount}get matchedCount(){return this.result.matchedCount}get modifiedCount(){return this.result.modifiedCount}get deletedCount(){return this.result.deletedCount}get upsertedCount(){return this.result.upsertedCount}get insertedIds(){return this.result.insertedIds}get upsertedIds(){return this.result.upsertedIds}}t.MongoBulkWriteError=S;class E{constructor(e){this.bulkOperation=e}update(e){const o=C(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.UPDATE,(0,c.makeUpdateStatement)(o.selector,e,{...o,multi:!0}))}updateOne(e){if(!(0,d.hasAtomicOperators)(e,this.bulkOperation.bsonOptions))throw new r.MongoInvalidArgumentError("Update document requires atomic operators");const o=C(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.UPDATE,(0,c.makeUpdateStatement)(o.selector,e,{...o,multi:!1}))}replaceOne(e){if((0,d.hasAtomicOperators)(e))throw new r.MongoInvalidArgumentError("Replacement document must not use atomic operators");const o=C(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.UPDATE,(0,c.makeUpdateStatement)(o.selector,e,{...o,multi:!1}))}deleteOne(){const e=C(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.DELETE,(0,i.makeDeleteStatement)(e.selector,{...e,limit:1}))}delete(){const e=C(this.bulkOperation);return this.bulkOperation.addToOperationsList(t.BatchType.DELETE,(0,i.makeDeleteStatement)(e.selector,{...e,limit:0}))}upsert(){return this.bulkOperation.s.currentOp||(this.bulkOperation.s.currentOp={}),this.bulkOperation.s.currentOp.upsert=!0,this}collation(e){return this.bulkOperation.s.currentOp||(this.bulkOperation.s.currentOp={}),this.bulkOperation.s.currentOp.collation=e,this}arrayFilters(e){return this.bulkOperation.s.currentOp||(this.bulkOperation.s.currentOp={}),this.bulkOperation.s.currentOp.arrayFilters=e,this}hint(e){return this.bulkOperation.s.currentOp||(this.bulkOperation.s.currentOp={}),this.bulkOperation.s.currentOp.hint=e,this}}function y(e){return e.batchType===t.BatchType.INSERT}function b(e){return e.batchType===t.BatchType.UPDATE}function O(e){return e.batchType===t.BatchType.DELETE}function C(e){let{currentOp:t}=e.s;return e.s.currentOp=void 0,t||(t={}),t}t.FindOperators=E,t.BulkOperationBase=class{constructor(e,t,o){this.collection=e,this.retryWrites=e.db.options?.retryWrites,this.isOrdered=o;const r=(0,d.getTopology)(e);t=null==t?{}:t;const i=e.s.namespace,s=r.lastHello(),a=!(!r.s.options||!r.s.options.autoEncrypter),c=s&&s.maxBsonObjectSize?s.maxBsonObjectSize:16777216,l=a?2097152:c,h=s&&s.maxWriteBatchSize?s.maxWriteBatchSize:1e3,m=(h-1).toString(10).length+2;this.s={bulkResult:{ok:1,writeErrors:[],writeConcernErrors:[],insertedIds:[],nInserted:0,nUpserted:0,nMatched:0,nModified:0,nRemoved:0,upserted:[]},currentBatch:void 0,currentIndex:0,currentBatchSize:0,currentBatchSizeBytes:0,currentInsertBatch:void 0,currentUpdateBatch:void 0,currentRemoveBatch:void 0,batches:[],writeConcern:u.WriteConcern.fromOptions(t),maxBsonObjectSize:c,maxBatchSizeBytes:l,maxWriteBatchSize:h,maxKeySize:m,namespace:i,topology:r,options:t,bsonOptions:(0,n.resolveBSONOptions)(t),currentOp:void 0,executed:!1,collection:e,err:void 0,checkKeys:"boolean"==typeof t.checkKeys&&t.checkKeys},!0===t.bypassDocumentValidation&&(this.s.bypassDocumentValidation=!0)}insert(e){return(0,d.maybeAddIdToDocuments)(this.collection,e,{forceServerObjectId:this.shouldForceServerObjectId()}),this.addToOperationsList(t.BatchType.INSERT,e)}find(e){if(!e)throw new r.MongoInvalidArgumentError("Bulk find operation must specify a selector");return this.s.currentOp={selector:e},new E(this)}raw(e){if(null==e||"object"!=typeof e)throw new r.MongoInvalidArgumentError("Operation must be an object with an operation key");if("insertOne"in e){const o=this.shouldForceServerObjectId(),n=e.insertOne&&null==e.insertOne.document?e.insertOne:e.insertOne.document;return(0,d.maybeAddIdToDocuments)(this.collection,n,{forceServerObjectId:o}),this.addToOperationsList(t.BatchType.INSERT,n)}if("replaceOne"in e||"updateOne"in e||"updateMany"in e){if("replaceOne"in e){if("q"in e.replaceOne)throw new r.MongoInvalidArgumentError("Raw operations are not allowed");const o=(0,c.makeUpdateStatement)(e.replaceOne.filter,e.replaceOne.replacement,{...e.replaceOne,multi:!1});if((0,d.hasAtomicOperators)(o.u))throw new r.MongoInvalidArgumentError("Replacement document must not use atomic operators");return this.addToOperationsList(t.BatchType.UPDATE,o)}if("updateOne"in e){if("q"in e.updateOne)throw new r.MongoInvalidArgumentError("Raw operations are not allowed");const o=(0,c.makeUpdateStatement)(e.updateOne.filter,e.updateOne.update,{...e.updateOne,multi:!1});if(!(0,d.hasAtomicOperators)(o.u,this.bsonOptions))throw new r.MongoInvalidArgumentError("Update document requires atomic operators");return this.addToOperationsList(t.BatchType.UPDATE,o)}if("updateMany"in e){if("q"in e.updateMany)throw new r.MongoInvalidArgumentError("Raw operations are not allowed");const o=(0,c.makeUpdateStatement)(e.updateMany.filter,e.updateMany.update,{...e.updateMany,multi:!0});if(!(0,d.hasAtomicOperators)(o.u,this.bsonOptions))throw new r.MongoInvalidArgumentError("Update document requires atomic operators");return this.addToOperationsList(t.BatchType.UPDATE,o)}}if("deleteOne"in e){if("q"in e.deleteOne)throw new r.MongoInvalidArgumentError("Raw operations are not allowed");return this.addToOperationsList(t.BatchType.DELETE,(0,i.makeDeleteStatement)(e.deleteOne.filter,{...e.deleteOne,limit:1}))}if("deleteMany"in e){if("q"in e.deleteMany)throw new r.MongoInvalidArgumentError("Raw operations are not allowed");return this.addToOperationsList(t.BatchType.DELETE,(0,i.makeDeleteStatement)(e.deleteMany.filter,{...e.deleteMany,limit:0}))}throw new r.MongoInvalidArgumentError("bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany")}get length(){return this.s.currentIndex}get bsonOptions(){return this.s.bsonOptions}get writeConcern(){return this.s.writeConcern}get batches(){const e=[...this.s.batches];return this.isOrdered?this.s.currentBatch&&e.push(this.s.currentBatch):(this.s.currentInsertBatch&&e.push(this.s.currentInsertBatch),this.s.currentUpdateBatch&&e.push(this.s.currentUpdateBatch),this.s.currentRemoveBatch&&e.push(this.s.currentRemoveBatch)),e}async execute(e={}){if(this.s.executed)throw new r.MongoBatchReExecutionError;const t=u.WriteConcern.fromOptions(e);if(t&&(this.s.writeConcern=t),this.isOrdered?this.s.currentBatch&&this.s.batches.push(this.s.currentBatch):(this.s.currentInsertBatch&&this.s.batches.push(this.s.currentInsertBatch),this.s.currentUpdateBatch&&this.s.batches.push(this.s.currentUpdateBatch),this.s.currentRemoveBatch&&this.s.batches.push(this.s.currentRemoveBatch)),0===this.s.batches.length)throw new r.MongoInvalidArgumentError("Invalid BulkOperation, Batch cannot be empty");this.s.executed=!0;const o=(0,d.resolveOptions)(this.collection,{...this.s.options,...e});return o.timeoutContext??=l.TimeoutContext.create({session:o.session,timeoutMS:o.timeoutMS,serverSelectionTimeoutMS:this.collection.client.s.options.serverSelectionTimeoutMS,waitQueueTimeoutMS:this.collection.client.s.options.waitQueueTimeoutMS}),null==o.session?await this.collection.client.withSession({explicit:!1},(async e=>await f(this,{...o,session:e}))):await f(this,{...o})}handleWriteError(e){if(this.s.bulkResult.writeErrors.length>0){const t=this.s.bulkResult.writeErrors[0].errmsg?this.s.bulkResult.writeErrors[0].errmsg:"write operation failed";throw new S({message:t,code:this.s.bulkResult.writeErrors[0].code,writeErrors:this.s.bulkResult.writeErrors},e)}const t=e.getWriteConcernError();if(t)throw new S(t,e)}shouldForceServerObjectId(){return!0===this.s.options.forceServerObjectId||!0===this.s.collection.db.options?.forceServerObjectId}}},82521:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReplaceOneOperation=t.UpdateManyOperation=t.UpdateOneOperation=t.UpdateOperation=void 0,t.makeUpdateStatement=m;const n=o(72216),r=o(36997),i=o(24007),s=o(30306),a=o(41539),c=o(28947);class l extends a.CommandOperation{constructor(e,t,o){super(void 0,o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=o,this.ns=e,this.statements=t}get commandName(){return"update"}get canRetryWrite(){return!1!==super.canRetryWrite&&this.statements.every((e=>null==e.multi||!1===e.multi))}buildCommandDocument(e,t){const o=this.options,n={update:this.ns.collection,updates:this.statements,ordered:o.ordered??!0};return"boolean"==typeof o.bypassDocumentValidation&&(n.bypassDocumentValidation=o.bypassDocumentValidation),o.let&&(n.let=o.let),void 0!==o.comment&&(n.comment=o.comment),n}}t.UpdateOperation=l;class d extends l{constructor(e,t,o,n){if(super(e,[m(t,o,{...n,multi:!1})],n),!(0,s.hasAtomicOperators)(o,n))throw new r.MongoInvalidArgumentError("Update document requires atomic operators")}handleOk(e){const t=super.handleOk(e);if(null!=this.explain)return t;if(t.code)throw new r.MongoServerError(t);if(t.writeErrors)throw new r.MongoServerError(t.writeErrors[0]);return{acknowledged:0!==this.writeConcern?.w,modifiedCount:t.nModified??t.n,upsertedId:Array.isArray(t.upserted)&&t.upserted.length>0?t.upserted[0]._id:null,upsertedCount:Array.isArray(t.upserted)&&t.upserted.length?t.upserted.length:0,matchedCount:Array.isArray(t.upserted)&&t.upserted.length>0?0:t.n}}}t.UpdateOneOperation=d;class u extends l{constructor(e,t,o,n){if(super(e,[m(t,o,{...n,multi:!0})],n),!(0,s.hasAtomicOperators)(o,n))throw new r.MongoInvalidArgumentError("Update document requires atomic operators")}handleOk(e){const t=super.handleOk(e);if(null!=this.explain)return t;if(t.code)throw new r.MongoServerError(t);if(t.writeErrors)throw new r.MongoServerError(t.writeErrors[0]);return{acknowledged:0!==this.writeConcern?.w,modifiedCount:t.nModified??t.n,upsertedId:Array.isArray(t.upserted)&&t.upserted.length>0?t.upserted[0]._id:null,upsertedCount:Array.isArray(t.upserted)&&t.upserted.length?t.upserted.length:0,matchedCount:Array.isArray(t.upserted)&&t.upserted.length>0?0:t.n}}}t.UpdateManyOperation=u;class h extends l{constructor(e,t,o,n){if(super(e,[m(t,o,{...n,multi:!1})],n),(0,s.hasAtomicOperators)(o))throw new r.MongoInvalidArgumentError("Replacement document must not contain atomic operators")}handleOk(e){const t=super.handleOk(e);if(null!=this.explain)return t;if(t.code)throw new r.MongoServerError(t);if(t.writeErrors)throw new r.MongoServerError(t.writeErrors[0]);return{acknowledged:0!==this.writeConcern?.w,modifiedCount:t.nModified??t.n,upsertedId:Array.isArray(t.upserted)&&t.upserted.length>0?t.upserted[0]._id:null,upsertedCount:Array.isArray(t.upserted)&&t.upserted.length?t.upserted.length:0,matchedCount:Array.isArray(t.upserted)&&t.upserted.length>0?0:t.n}}}function m(e,t,o){if(null==e||"object"!=typeof e)throw new r.MongoInvalidArgumentError("Selector must be a valid JavaScript object");if(null==t||"object"!=typeof t)throw new r.MongoInvalidArgumentError("Document must be a valid JavaScript object");const n={q:e,u:t};return"boolean"==typeof o.upsert&&(n.upsert=o.upsert),o.multi&&(n.multi=o.multi),o.hint&&(n.hint=o.hint),o.arrayFilters&&(n.arrayFilters=o.arrayFilters),o.collation&&(n.collation=o.collation),o.multi||null==o.sort||(n.sort=(0,i.formatSort)(o.sort)),n}t.ReplaceOneOperation=h,(0,c.defineAspects)(l,[c.Aspect.RETRYABLE,c.Aspect.WRITE_OPERATION,c.Aspect.SKIP_COLLATION,c.Aspect.SUPPORTS_RAW_DATA]),(0,c.defineAspects)(d,[c.Aspect.RETRYABLE,c.Aspect.WRITE_OPERATION,c.Aspect.EXPLAINABLE,c.Aspect.SKIP_COLLATION,c.Aspect.SUPPORTS_RAW_DATA]),(0,c.defineAspects)(u,[c.Aspect.WRITE_OPERATION,c.Aspect.EXPLAINABLE,c.Aspect.SKIP_COLLATION,c.Aspect.SUPPORTS_RAW_DATA]),(0,c.defineAspects)(h,[c.Aspect.RETRYABLE,c.Aspect.WRITE_OPERATION,c.Aspect.SKIP_COLLATION,c.Aspect.SUPPORTS_RAW_DATA])},83811:function(e,t,o){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.generateUri=function(e){if(e.nodb)return"";const t=function(e){const t=e.connectionSpecifier,{replSetName:o,hosts:n}=function(e){if(!e)return{};const[t,o,...n]=e.split("/").reverse();if(n.length)return{};const r=t.split(",").filter(Boolean);return r.every((e=>/^([A-Za-z0-9._-]+|\[[0-9a-fA-F:]+\])(:\d+)?$/.test(e)))?{replSetName:o,hosts:r}:{}}(e.host);if(o||(n??[]).length>1){const a=new s.ConnectionString(`mongodb://replacemeHost/${encodeURIComponent(t||"")}`);return a.hosts=function(e,t){const o=[];for(const n of e){const{host:e,port:s}=/^(?<host>.+?)(:(?<port>\d+))?$/.exec(n)?.groups??{};if(t&&void 0!==s&&s!==t)throw new r.MongoshInvalidInputError(i.default.__(u),r.CommonErrors.InvalidArgument);o.push(`${e}${s||t?`:${s||t}`:""}`)}return o}(n??[],e.port),o&&a.searchParams.set("replicaSet",o),E(a)}if(!t)return new s.ConnectionString(`mongodb://${f(e)}:${S(e)}/?directConnection=true`);if(t.startsWith("mongodb+srv://")){const o=new s.ConnectionString(t);return p(e,o),o}if(t.startsWith("mongodb://")){const o=new s.ConnectionString(t);return p(e,o),E(o)}let a=/^([A-Za-z0-9][A-Za-z0-9._-]+)(?::(\d+))?(?:\/(\S*))?$/gi.exec(t);if(null===a){if(/[/\\. "$]/.test(t))throw new r.MongoshInvalidInputError(`Invalid URI: ${t}`,r.CommonErrors.InvalidArgument);a=[t,t]}let c=a?.[1];const l=a?.[2];let d=a?.[3];return!l&&!d&&c.indexOf(".")<0&&(d=c,c=void 0),(c||l)&&p(e),E(new s.ConnectionString(`mongodb://${c||f(e)}:${l||S(e)}/${encodeURIComponent(d||"")}`))}(e);if(t.hosts.every((e=>["localhost","127.0.0.1"].includes(e.split(":")[0])))){const e=t.searchParams;e.has("serverSelectionTimeoutMS")||e.set("serverSelectionTimeoutMS","2000")}return t.toString()};const r=o(92762),i=n(o(96109)),s=o(42344),a="127.0.0.1",c="27017",l="cli-repl.uri-generator.no-host-port",d="cli-repl.uri-generator.invalid-host",u="cli-repl.uri-generator.host-list-port-mismatch",h="cli-repl.uri-generator.diverging-service-name",m="cli-repl.uri-generator.gssapi-service-name-unsupported";function p(e,t){if(e.host||e.port)throw new r.MongoshInvalidInputError(i.default.__(l),r.CommonErrors.InvalidArgument);if(e.gssapiServiceName&&t?.searchParams.has("authMechanismProperties")){const o=new s.CommaAndColonSeparatedRecord(t.searchParams.get("authMechanismProperties")).get("SERVICE_NAME");if(void 0!==o&&e.gssapiServiceName!==o)throw new r.MongoshInvalidInputError(i.default.__(h),r.CommonErrors.InvalidArgument)}if(t?.searchParams.has("gssapiServiceName"))throw new r.MongoshInvalidInputError(i.default.__(m),r.CommonErrors.InvalidArgument)}function g(e){const t=/[^a-zA-Z0-9.:[\]_-]/.exec(e);if(t)throw new r.MongoshInvalidInputError(`${i.default.__(d)}: ${t[0]}`,r.CommonErrors.InvalidArgument)}function f(e){return e.host?(g(e.host),e.host.includes(":")?e.host.split(":")[0]:e.host):a}function S(e){if(e.host&&e.host.includes(":")){g(e.host);const t=e.host.split(":")[1];if(!e.port||e.port===t)return t;throw new r.MongoshInvalidInputError(i.default.__(l),r.CommonErrors.InvalidArgument)}return e.port?e.port:c}function E(e){const t=(e=e.clone()).searchParams;return t.has("replicaSet")||t.has("directConnection")||t.has("loadBalanced")||1!==e.hosts.length||t.set("directConnection","true"),e}},84715:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CreateCollectionOperation=void 0,t.createCollections=async function(e,t,o){const r=a.TimeoutContext.create({session:o.session,serverSelectionTimeoutMS:e.client.s.options.serverSelectionTimeoutMS,waitQueueTimeoutMS:e.client.s.options.waitQueueTimeoutMS,timeoutMS:o.timeoutMS}),i=o.encryptedFields??e.client.s.options.autoEncryption?.encryptedFieldsMap?.[`${e.databaseName}.${t}`];if(i){class a extends g{buildCommandDocument(e,t){if(!e.description.loadBalanced&&(0,c.maxWireVersion)(e)<n.MIN_SUPPORTED_QE_WIRE_VERSION)throw new s.MongoCompatibilityError(`${p} The minimum server version required is ${n.MIN_SUPPORTED_QE_SERVER_VERSION}`);return super.buildCommandDocument(e,t)}}const l=i.escCollection??`enxcol_.${t}.esc`,u=i.ecocCollection??`enxcol_.${t}.ecoc`;for(const t of[l,u]){const n=new a(e,t,{clusteredIndex:{key:{_id:1},unique:!0},session:o.session});await(0,d.executeOperation)(e.client,n,r)}o.encryptedFields||(o={...o,encryptedFields:i})}const l=await(0,d.executeOperation)(e.client,new g(e,t,o),r);if(i){const n=u.CreateIndexesOperation.fromIndexSpecification(e,t,{__safeContent__:1},{session:o.session});await(0,d.executeOperation)(e.client,n,r)}return l};const n=o(60889),r=o(72216),i=o(53975),s=o(36997),a=o(33628),c=o(30306),l=o(41539),d=o(39131),u=o(15002),h=o(28947),m=new Set(["w","wtimeout","timeoutMS","j","fsync","pkFactory","raw","readPreference","session","readConcern","writeConcern","raw","fieldsAsRaw","useBigInt64","promoteLongs","promoteValues","promoteBuffers","bsonRegExp","serializeFunctions","ignoreUndefined","enableUtf8Validation"]),p="Driver support of Queryable Encryption is incompatible with server. Upgrade server to use Queryable Encryption.";class g extends l.CommandOperation{constructor(e,t,o={}){super(e,o),this.SERVER_COMMAND_RESPONSE_TYPE=r.MongoDBResponse,this.options=o,this.db=e,this.name=t}get commandName(){return"create"}buildCommandDocument(e,t){return{create:this.name,...Object.fromEntries(Object.entries(this.options).filter((([e,t])=>null!=t&&"function"!=typeof t&&!m.has(e))))}}handleOk(e){return new i.Collection(this.db,this.name,this.options)}}t.CreateCollectionOperation=g,(0,h.defineAspects)(g,[h.Aspect.WRITE_OPERATION])},84778:(e,t,o)=>{var n=o(34110).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.LimitedSizeDocument=void 0,t.isDriverInfoEqual=function(e,t){const o=(e,t)=>(e||=void 0,t||=void 0,e===t);return o(e.name,t.name)&&o(e.platform,t.platform)&&o(e.version,t.version)},t.makeClientMetadata=async function(e,{appName:t=""}){const o=new d(512);if(t.length>0){const e=n.byteLength(t,"utf8")<=128?t:n.from(t,"utf8").subarray(0,128).toString("utf8");o.ifItFitsItSits("application",{name:e})}const m={name:"nodejs",version:l};for(const{name:t="",version:o=""}of e)t.length>0&&(m.name=`${m.name}|${t}`),o.length>0&&(m.version=`${m.version}|${o}`);if(!o.ifItFitsItSits("driver",m))throw new a.MongoInvalidArgumentError("Unable to include driverInfo name and version, metadata cannot exceed 512 bytes");let p=function(){const e=s.NumberUtils.isBigEndian?"BE":"LE";return"Deno"in globalThis?`Deno v${"string"==typeof Deno?.version?.deno?Deno?.version?.deno:"0.0.0-unknown"}, ${e}`:"Bun"in globalThis?`Bun v${"string"==typeof Bun?.version?Bun?.version:"0.0.0-unknown"}, ${e}`:`Node.js ${i.version}, ${e}`}();for(const{platform:t=""}of e)t.length>0&&(p=`${p}|${t}`);if(!o.ifItFitsItSits("platform",p))throw new a.MongoInvalidArgumentError("Unable to include driverInfo platform, metadata cannot exceed 512 bytes");const g=(new Map).set("name",r.platform()).set("architecture",r.arch()).set("version",r.release()).set("type",r.type());if(!o.ifItFitsItSits("os",g))for(const e of g.keys()){if(g.delete(e),0===g.size)break;if(o.ifItFitsItSits("os",g))break}const f=h();if(null!=f&&!o.ifItFitsItSits("env",f))for(const e of f.keys()){if(f.delete(e),0===f.size)break;if(o.ifItFitsItSits("env",f))break}return await async function(e){const t=await async function(){u??=(0,c.fileIsAccessible)("/.dockerenv");const e=await u,{KUBERNETES_SERVICE_HOST:t=""}=i.env,o=t.length>0,n={};return e&&(n.runtime="docker"),o&&(n.orchestrator="kubernetes"),n}();if(0===Object.keys(t).length)return e;const o=new d(512),n={...e?.env,container:t};for(const[t,r]of Object.entries(e))"env"!==t?o.ifItFitsItSits(t,r):o.ifItFitsItSits("env",n)||o.ifItFitsItSits("env",r);return"env"in e||o.ifItFitsItSits("env",n),o.toObject()}(o.toObject())},t.getFAASEnv=h;const r=o(87098),i=o(15088),s=o(77953),a=o(36997),c=o(30306),l=o(46195).rE;class d{constructor(e){this.document=new Map,this.documentSize=5,this.maxSize=e}ifItFitsItSits(e,t){const o=s.BSON.serialize((new Map).set(e,t)).byteLength-5;return!(o+this.documentSize>this.maxSize||(this.documentSize+=o,this.document.set(e,t),0))}toObject(){return s.BSON.deserialize(s.BSON.serialize(this.document),{promoteLongs:!1,promoteBuffers:!1,promoteValues:!1,useBigInt64:!1})}}let u;function h(){const{AWS_EXECUTION_ENV:e="",AWS_LAMBDA_RUNTIME_API:t="",FUNCTIONS_WORKER_RUNTIME:o="",K_SERVICE:n="",FUNCTION_NAME:r="",VERCEL:a="",AWS_LAMBDA_FUNCTION_MEMORY_SIZE:c="",AWS_REGION:l="",FUNCTION_MEMORY_MB:d="",FUNCTION_REGION:u="",FUNCTION_TIMEOUT_SEC:h="",VERCEL_REGION:m=""}=i.env,p=e.startsWith("AWS_Lambda_")||t.length>0,g=o.length>0,f=n.length>0||r.length>0,S=a.length>0,E=new Map;return!S||g||f?p&&!(g||f||S)?(l.length>0&&E.set("region",l),c.length>0&&Number.isInteger(+c)&&E.set("memory_mb",new s.Int32(c)),E.set("name","aws.lambda"),E):g&&!(f||p||S)?(E.set("name","azure.func"),E):f&&!(g||p||S)?(u.length>0&&E.set("region",u),d.length>0&&Number.isInteger(+d)&&E.set("memory_mb",new s.Int32(d)),h.length>0&&Number.isInteger(+h)&&E.set("timeout_sec",new s.Int32(h)),E.set("name","gcp.func"),E):null:(m.length>0&&E.set("region",m),E.set("name","vercel"),E)}t.LimitedSizeDocument=d},85052:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RemoveUserOperation=void 0;const n=o(72216),r=o(41539),i=o(28947);class s extends r.CommandOperation{constructor(e,t,o){super(e,o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=o,this.username=t}get commandName(){return"dropUser"}buildCommandDocument(e){return{dropUser:this.username}}handleOk(e){return!0}}t.RemoveUserOperation=s,(0,i.defineAspects)(s,[i.Aspect.WRITE_OPERATION])},85407:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListCollectionsCursor=void 0;const n=o(39131),r=o(66022),i=o(40927);class s extends i.AbstractCursor{constructor(e,t,o){super(e.client,e.s.namespace,o),this.parent=e,this.filter=t,this.options=o}clone(){return new s(this.parent,this.filter,{...this.options,...this.cursorOptions})}async _initialize(e){const t=new r.ListCollectionsOperation(this.parent,this.filter,{...this.cursorOptions,...this.options,session:e,signal:this.signal}),o=await(0,n.executeOperation)(this.parent.client,t,this.timeoutContext);return{server:t.server,session:e,response:o}}}t.ListCollectionsCursor=s},85673:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CountOperation=void 0;const n=o(72216),r=o(41539),i=o(28947);class s extends r.CommandOperation{constructor(e,t,o){super({s:{namespace:e}},o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=o,this.collectionName=e.collection,this.query=t}get commandName(){return"count"}buildCommandDocument(e,t){const o=this.options,n={count:this.collectionName,query:this.query};return"number"==typeof o.limit&&(n.limit=o.limit),"number"==typeof o.skip&&(n.skip=o.skip),null!=o.hint&&(n.hint=o.hint),"number"==typeof o.maxTimeMS&&(n.maxTimeMS=o.maxTimeMS),n}handleOk(e){return e.getNumber("n")??0}}t.CountOperation=s,(0,i.defineAspects)(s,[i.Aspect.READ_OPERATION,i.Aspect.RETRYABLE,i.Aspect.SUPPORTS_RAW_DATA])},85744:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEmptyCredentials=s,t.refreshKMSCredentials=async function(e,t){let o=e;return s("aws",e)&&(o=await(0,n.loadAWSCredentials)(o,t?.aws)),s("gcp",e)&&(o=await(0,i.loadGCPCredentials)(o)),s("azure",e)&&(o=await(0,r.loadAzureCredentials)(o)),o};const n=o(20753),r=o(43975),i=o(41374);function s(e,t){const o=t[e];return null!=o&&"object"==typeof o&&0===Object.keys(o).length}},86065:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AggregateOperation=t.DB_AGGREGATE_COLLECTION=void 0;const n=o(72216),r=o(36997),i=o(71259),s=o(41539),a=o(28947);t.DB_AGGREGATE_COLLECTION=1;class c extends s.CommandOperation{constructor(e,o,i){if(super(void 0,{...i,dbName:e.db}),this.SERVER_COMMAND_RESPONSE_TYPE=n.CursorResponse,this.options={...i},this.target=e.collection||t.DB_AGGREGATE_COLLECTION,this.pipeline=o,this.hasWriteStage=!1,"string"==typeof i?.out)this.pipeline=this.pipeline.concat({$out:i.out}),this.hasWriteStage=!0;else if(o.length>0){const e=o[o.length-1];(e.$out||e.$merge)&&(this.hasWriteStage=!0)}if(this.hasWriteStage||delete this.options.writeConcern,null!=i?.cursor&&"object"!=typeof i.cursor)throw new r.MongoInvalidArgumentError("Cursor options must be an object");this.SERVER_COMMAND_RESPONSE_TYPE=this.explain?n.ExplainedCursorResponse:n.CursorResponse}get commandName(){return"aggregate"}get canRetryRead(){return!this.hasWriteStage}addToPipeline(e){this.pipeline.push(e)}buildCommandDocument(){const e=this.options,t={aggregate:this.target,pipeline:this.pipeline};return this.hasWriteStage&&this.writeConcern&&i.WriteConcern.apply(t,this.writeConcern),!0===e.bypassDocumentValidation&&(t.bypassDocumentValidation=e.bypassDocumentValidation),"boolean"==typeof e.allowDiskUse&&(t.allowDiskUse=e.allowDiskUse),e.hint&&(t.hint=e.hint),e.let&&(t.let=e.let),void 0!==e.comment&&(t.comment=e.comment),t.cursor=e.cursor||{},e.batchSize&&!this.hasWriteStage&&(t.cursor.batchSize=e.batchSize),t}handleOk(e){return e}}t.AggregateOperation=c,(0,a.defineAspects)(c,[a.Aspect.READ_OPERATION,a.Aspect.RETRYABLE,a.Aspect.EXPLAINABLE,a.Aspect.CURSOR_CREATING,a.Aspect.SUPPORTS_RAW_DATA])},86098:(e,t,o)=>{var n=o(34110).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.ServerSessionPool=t.ServerSession=t.ClientSession=void 0,t.maybeClearPinnedConnection=T,t.applySession=function(e,t,o){if(e.hasEnded)return new c.MongoExpiredSessionError;const n=e.serverSession;if(null==n)return new c.MongoRuntimeError("Unable to acquire server session");if(0===o.writeConcern?.w)return e&&e.explicit?new c.MongoAPIError("Cannot have explicit session with unacknowledged writes"):void 0;n.lastUse=(0,S.processTimeMS)(),t.lsid=n.id;const r=e.inTransaction()||(0,f.isTransactionCommand)(t);if((o.willRetryWrite||r)&&(n.txnNumber+=e.txnNumberIncrement,e.txnNumberIncrement=0,t.txnNumber=i.Long.fromNumber(n.txnNumber)),!r)return e.transaction.state!==f.TxnState.NO_TRANSACTION&&e.transaction.transition(f.TxnState.NO_TRANSACTION),void(e.supports.causalConsistency&&e.operationTime&&(0,S.commandSupportsReadConcern)(t)?(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime})):e.snapshotEnabled&&(t.readConcern=t.readConcern||{level:h.ReadConcernLevel.snapshot},null!=e.snapshotTime&&Object.assign(t.readConcern,{atClusterTime:e.snapshotTime})));if(t.autocommit=!1,e.transaction.state===f.TxnState.STARTING_TRANSACTION){e.transaction.transition(f.TxnState.TRANSACTION_IN_PROGRESS),t.startTransaction=!0;const o=e.transaction.options.readConcern||e?.clientOptions?.readConcern;o&&(t.readConcern=o),e.supports.causalConsistency&&e.operationTime&&(t.readConcern=t.readConcern||{},Object.assign(t.readConcern,{afterClusterTime:e.operationTime}))}},t.updateSessionFromResponse=function(e,t){if(t.$clusterTime&&(0,p._advanceClusterTime)(e,t.$clusterTime),t.operationTime&&e&&e.supports.causalConsistency&&e.advanceOperationTime(t.operationTime),t.recoveryToken&&e&&e.inTransaction()&&(e.transaction._recoveryToken=t.recoveryToken),e?.snapshotEnabled&&null==e.snapshotTime){const o=t.atClusterTime;o&&(e.snapshotTime=o)}};const r=o(31713),i=o(77953),s=o(67204),a=o(34842),c=o(36997),l=o(72361),d=o(39131),u=o(9405),h=o(86552),m=o(74891),p=o(90648),g=o(33628),f=o(67518),S=o(30306),E=o(71259);class y extends l.TypedEventEmitter{constructor(e,t,o,n){if(super(),this.timeoutContext=null,this.on("error",S.noop),null==e)throw new c.MongoRuntimeError("ClientSession requires a MongoClient");if(null==t||!(t instanceof R))throw new c.MongoRuntimeError("ClientSession requires a ServerSessionPool");if(o=o??{},this.snapshotEnabled=!0===o.snapshot,!0===o.causalConsistency&&this.snapshotEnabled)throw new c.MongoInvalidArgumentError('Properties "causalConsistency" and "snapshot" are mutually exclusive');this.client=e,this.sessionPool=t,this.hasEnded=!1,this.clientOptions=n,this.timeoutMS=o.defaultTimeoutMS??e.s.options?.timeoutMS,this.explicit=!!o.explicit,this._serverSession=this.explicit?this.sessionPool.acquire():null,this.txnNumberIncrement=0;const r=this.explicit&&!0!==o.snapshot;this.supports={causalConsistency:o.causalConsistency??r},this.clusterTime=o.initialClusterTime,this.operationTime=void 0,this.owner=o.owner,this.defaultTransactionOptions={...o.defaultTransactionOptions},this.transaction=new f.Transaction}get id(){return this.serverSession?.id}get serverSession(){let e=this._serverSession;if(null==e){if(this.explicit)throw new c.MongoRuntimeError("Unexpected null serverSession for an explicit session");if(this.hasEnded)throw new c.MongoRuntimeError("Unexpected null serverSession for an ended implicit session");e=this.sessionPool.acquire(),this._serverSession=e}return e}get loadBalanced(){return this.client.topology?.description.type===p.TopologyType.LoadBalanced}pin(e){if(this.pinnedConnection)throw TypeError("Cannot pin multiple connections to the same session");this.pinnedConnection=e,e.emit(a.PINNED,this.inTransaction()?s.ConnectionPoolMetrics.TXN:s.ConnectionPoolMetrics.CURSOR)}unpin(e){if(this.loadBalanced)return T(this,e);this.transaction.unpinServer()}get isPinned(){return this.loadBalanced?!!this.pinnedConnection:this.transaction.isPinned}async endSession(e){try{this.inTransaction()&&await this.abortTransaction({...e,throwTimeout:!0})}catch(e){if("MongoOperationTimeoutError"===e.name)throw e;(0,S.squashError)(e)}finally{if(!this.hasEnded){const e=this.serverSession;null!=e&&(this.sessionPool.release(e),this._serverSession=new v(e)),this.hasEnded=!0,this.emit("ended",this)}T(this,{force:!0,...e})}}async[Symbol.asyncDispose](){await this.endSession({force:!0})}advanceOperationTime(e){null!=this.operationTime?e.greaterThan(this.operationTime)&&(this.operationTime=e):this.operationTime=e}advanceClusterTime(e){if(!e||"object"!=typeof e)throw new c.MongoInvalidArgumentError("input cluster time must be an object");if(!e.clusterTime||"Timestamp"!==e.clusterTime._bsontype)throw new c.MongoInvalidArgumentError('input cluster time "clusterTime" property must be a valid BSON Timestamp');if(!e.signature||"Binary"!==e.signature.hash?._bsontype||"bigint"!=typeof e.signature.keyId&&"number"!=typeof e.signature.keyId&&"Long"!==e.signature.keyId?._bsontype)throw new c.MongoInvalidArgumentError('input cluster time must have a valid "signature" property with BSON Binary hash and BSON Long keyId');(0,p._advanceClusterTime)(this,e)}equals(e){return e instanceof y&&null!=this.id&&null!=e.id&&S.ByteUtils.equals(this.id.id.buffer,e.id.id.buffer)}incrementTransactionNumber(){this.txnNumberIncrement+=1}inTransaction(){return this.transaction.isActive}startTransaction(e){if(this.snapshotEnabled)throw new c.MongoCompatibilityError("Transactions are not supported in snapshot sessions");if(this.inTransaction())throw new c.MongoTransactionError("Transaction already in progress");this.isPinned&&this.transaction.isCommitted&&this.unpin(),this.commitAttempted=!1,this.incrementTransactionNumber(),this.transaction=new f.Transaction({readConcern:e?.readConcern??this.defaultTransactionOptions.readConcern??this.clientOptions?.readConcern,writeConcern:e?.writeConcern??this.defaultTransactionOptions.writeConcern??this.clientOptions?.writeConcern,readPreference:e?.readPreference??this.defaultTransactionOptions.readPreference??this.clientOptions?.readPreference,maxCommitTimeMS:e?.maxCommitTimeMS??this.defaultTransactionOptions.maxCommitTimeMS}),this.transaction.transition(f.TxnState.STARTING_TRANSACTION)}async commitTransaction(e){if(this.transaction.state===f.TxnState.NO_TRANSACTION)throw new c.MongoTransactionError("No transaction started");if(this.transaction.state===f.TxnState.STARTING_TRANSACTION||this.transaction.state===f.TxnState.TRANSACTION_COMMITTED_EMPTY)return void this.transaction.transition(f.TxnState.TRANSACTION_COMMITTED_EMPTY);if(this.transaction.state===f.TxnState.TRANSACTION_ABORTED)throw new c.MongoTransactionError("Cannot call commitTransaction after calling abortTransaction");const t={commitTransaction:1},o="number"==typeof e?.timeoutMS?e.timeoutMS:"number"==typeof this.timeoutMS?this.timeoutMS:null,n=this.transaction.options.writeConcern??this.clientOptions?.writeConcern;if(null!=n)if(null==o&&null==this.timeoutContext)E.WriteConcern.apply(t,{wtimeoutMS:1e4,w:"majority",...n});else{const e=Object.keys(n);(e.length>2||!e.includes("wtimeoutMS")&&!e.includes("wTimeoutMS"))&&E.WriteConcern.apply(t,{...n,wtimeoutMS:void 0})}(this.transaction.state===f.TxnState.TRANSACTION_COMMITTED||this.commitAttempted)&&(null==o&&null==this.timeoutContext?E.WriteConcern.apply(t,{wtimeoutMS:1e4,...n,w:"majority"}):E.WriteConcern.apply(t,{w:"majority",...n,wtimeoutMS:void 0})),"number"==typeof this.transaction.options.maxTimeMS&&(t.maxTimeMS=this.transaction.options.maxTimeMS),this.transaction.recoveryToken&&(t.recoveryToken=this.transaction.recoveryToken);const r=new u.RunCommandOperation(new S.MongoDBNamespace("admin"),t,{session:this,readPreference:m.ReadPreference.primary,bypassPinningCheck:!0}),i=this.timeoutContext??("number"==typeof o?g.TimeoutContext.create({serverSelectionTimeoutMS:this.clientOptions.serverSelectionTimeoutMS,socketTimeoutMS:this.clientOptions.socketTimeoutMS,timeoutMS:o}):null);try{return await(0,d.executeOperation)(this.client,r,i),void(this.commitAttempted=void 0)}catch(e){if(this.commitAttempted=!0,e instanceof c.MongoError&&(0,c.isRetryableWriteError)(e)){E.WriteConcern.apply(t,{wtimeoutMS:1e4,...n,w:"majority"}),this.unpin({force:!0});try{return void await(0,d.executeOperation)(this.client,new u.RunCommandOperation(new S.MongoDBNamespace("admin"),t,{session:this,readPreference:m.ReadPreference.primary,bypassPinningCheck:!0}),i)}catch(e){throw C(e)&&e.addErrorLabel(c.MongoErrorLabel.UnknownTransactionCommitResult),O(e)&&this.unpin({error:e}),e}}throw C(e)&&e.addErrorLabel(c.MongoErrorLabel.UnknownTransactionCommitResult),O(e)&&this.unpin({error:e}),e}finally{this.transaction.transition(f.TxnState.TRANSACTION_COMMITTED)}}async abortTransaction(e){if(this.transaction.state===f.TxnState.NO_TRANSACTION)throw new c.MongoTransactionError("No transaction started");if(this.transaction.state===f.TxnState.STARTING_TRANSACTION)return void this.transaction.transition(f.TxnState.TRANSACTION_ABORTED);if(this.transaction.state===f.TxnState.TRANSACTION_ABORTED)throw new c.MongoTransactionError("Cannot call abortTransaction twice");if(this.transaction.state===f.TxnState.TRANSACTION_COMMITTED||this.transaction.state===f.TxnState.TRANSACTION_COMMITTED_EMPTY)throw new c.MongoTransactionError("Cannot call abortTransaction after calling commitTransaction");const t={abortTransaction:1},o="number"==typeof e?.timeoutMS?e.timeoutMS:this.timeoutContext?.csotEnabled()?this.timeoutContext.timeoutMS:"number"==typeof this.timeoutMS?this.timeoutMS:null,n=null!=o?g.TimeoutContext.create({timeoutMS:o,serverSelectionTimeoutMS:this.clientOptions.serverSelectionTimeoutMS,socketTimeoutMS:this.clientOptions.socketTimeoutMS}):null,r=this.transaction.options.writeConcern??this.clientOptions?.writeConcern;null!=r&&null==o&&E.WriteConcern.apply(t,{wtimeoutMS:1e4,w:"majority",...r}),this.transaction.recoveryToken&&(t.recoveryToken=this.transaction.recoveryToken);const i=new u.RunCommandOperation(new S.MongoDBNamespace("admin"),t,{session:this,readPreference:m.ReadPreference.primary,bypassPinningCheck:!0});try{return await(0,d.executeOperation)(this.client,i,n),void this.unpin()}catch(t){if(this.unpin(),"MongoRuntimeError"===t.name)throw t;if(e?.throwTimeout&&"MongoOperationTimeoutError"===t.name)throw t;if(t instanceof c.MongoError&&(0,c.isRetryableWriteError)(t))try{return void await(0,d.executeOperation)(this.client,i,n)}catch(t){if("MongoRuntimeError"===t.name)throw t;if(e?.throwTimeout&&"MongoOperationTimeoutError"===t.name)throw t}}finally{this.transaction.transition(f.TxnState.TRANSACTION_ABORTED),this.loadBalanced&&T(this,{force:!1})}}toBSON(){throw new c.MongoRuntimeError("ClientSession cannot be serialized to BSON.")}async withTransaction(e,t){const o=12e4,n=t?.timeoutMS??this.timeoutMS??null;this.timeoutContext=null!=n?g.TimeoutContext.create({timeoutMS:n,serverSelectionTimeoutMS:this.clientOptions.serverSelectionTimeoutMS,socketTimeoutMS:this.clientOptions.socketTimeoutMS}):null;const i=this.timeoutContext?.csotEnabled()?this.timeoutContext.start:(0,S.processTimeMS)();let s,a=!1,l=null;try{e:for(let n=0,d=!1;!a;++n,d=n>0){if(d){const e=5,t=500,s=1.5,a=Math.random()*Math.min(e*s**(n-1),t);if(this.timeoutContext?.csotEnabled()&&a>this.timeoutContext.remainingTimeMS||(0,S.processTimeMS)()+a>i+o)throw l??new c.MongoRuntimeError("Transaction retry did not record an error: should never occur. Please file a bug.");await(0,r.setTimeout)(a)}this.startTransaction(t);try{const t=e(this);if(!(0,S.isPromiseLike)(t))throw new c.MongoInvalidArgumentError("Function provided to `withTransaction` must return a Promise");if(s=await t,this.transaction.state===f.TxnState.NO_TRANSACTION||this.transaction.state===f.TxnState.TRANSACTION_COMMITTED||this.transaction.state===f.TxnState.TRANSACTION_ABORTED)return s}catch(e){if(!(e instanceof c.MongoError)||e instanceof c.MongoInvalidArgumentError)throw await this.abortTransaction(),e;if(this.transaction.state!==f.TxnState.STARTING_TRANSACTION&&this.transaction.state!==f.TxnState.TRANSACTION_IN_PROGRESS||await this.abortTransaction(),e.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError)&&(this.timeoutContext?.csotEnabled()||(0,S.processTimeMS)()-i<o)){l=e;continue e}throw e}t:for(;!a;)try{await this.commitTransaction(),a=!0}catch(e){if(this.timeoutContext?.csotEnabled()||!((0,S.processTimeMS)()-i>=o)){if(!w(e)&&e.hasErrorLabel(c.MongoErrorLabel.UnknownTransactionCommitResult))continue t;if(e.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError)){l=e;continue e}}throw e}}return s}finally{this.timeoutContext=null}}}t.ClientSession=y;const b=new Set(["CannotSatisfyWriteConcern","UnknownReplWriteConcern","UnsatisfiableWriteConcern"]);function O(e){if(e instanceof c.MongoError)if((0,c.isRetryableWriteError)(e)||e instanceof c.MongoWriteConcernError||w(e)){if(M(e))return!0}else if(e.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError))return!0;return!1}function C(e){let t=(0,c.isRetryableWriteError)(e);return t||=e instanceof c.MongoWriteConcernError,t||=w(e),t&&=M(e),t}function M(e){const t=e instanceof c.MongoServerError&&e.codeName&&b.has(e.codeName);return w(e)||!t&&e.code!==c.MONGODB_ERROR_CODES.UnsatisfiableWriteConcern&&e.code!==c.MONGODB_ERROR_CODES.UnknownReplWriteConcern}function T(e,t){const o=e.pinnedConnection,n=t?.error;if(e.inTransaction()&&n&&n instanceof c.MongoError&&n.hasErrorLabel(c.MongoErrorLabel.TransientTransactionError))return;const r=e.client.topology;if(o&&null!=r){const n=Array.from(r.s.servers.values())[0];(null==t?.error||t?.force)&&(n.pool.checkIn(o),e.pinnedConnection=void 0,o.emit(a.UNPINNED,e.transaction.state!==f.TxnState.NO_TRANSACTION?s.ConnectionPoolMetrics.TXN:s.ConnectionPoolMetrics.CURSOR),t?.forceClear&&n.pool.clear({serviceId:o.serviceId}))}}function w(e){return null!=e&&e instanceof c.MongoServerError&&(e.code===c.MONGODB_ERROR_CODES.MaxTimeMSExpired||e.writeConcernError?.code===c.MONGODB_ERROR_CODES.MaxTimeMSExpired)}class v{constructor(e){if(null!=e){const t=n.allocUnsafe(16);return t.set(e.id.id.buffer),this.id={id:new i.Binary(t,e.id.id.sub_type)},this.lastUse=e.lastUse,this.txnNumber=e.txnNumber,void(this.isDirty=e.isDirty)}this.id={id:new i.Binary((0,S.uuidV4)(),i.Binary.SUBTYPE_UUID)},this.lastUse=(0,S.processTimeMS)(),this.txnNumber=0,this.isDirty=!1}hasTimedOut(e){return Math.round((0,S.calculateDurationInMs)(this.lastUse)%864e5%36e5/6e4)>e-1}}t.ServerSession=v;class R{constructor(e){if(null==e)throw new c.MongoRuntimeError("ServerSessionPool requires a MongoClient");this.client=e,this.sessions=new S.List}acquire(){const e=this.client.topology?.logicalSessionTimeoutMinutes??10;let t=null;for(;this.sessions.length>0;){const o=this.sessions.shift();if(null!=o&&(this.client.topology?.loadBalanced||!o.hasTimedOut(e))){t=o;break}}return null==t&&(t=new v),t}release(e){const t=this.client.topology?.logicalSessionTimeoutMinutes??10;if(this.client.topology?.loadBalanced&&!t&&this.sessions.unshift(e),t&&(this.sessions.prune((e=>e.hasTimedOut(t))),!e.hasTimedOut(t))){if(e.isDirty)return;this.sessions.unshift(e)}}}t.ServerSessionPool=R},86348:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServerHeartbeatFailedEvent=t.ServerHeartbeatSucceededEvent=t.ServerHeartbeatStartedEvent=t.TopologyClosedEvent=t.TopologyOpeningEvent=t.TopologyDescriptionChangedEvent=t.ServerClosedEvent=t.ServerOpeningEvent=t.ServerDescriptionChangedEvent=void 0;const n=o(34842);t.ServerDescriptionChangedEvent=class{constructor(e,t,o,r){this.name=n.SERVER_DESCRIPTION_CHANGED,this.topologyId=e,this.address=t,this.previousDescription=o,this.newDescription=r}},t.ServerOpeningEvent=class{constructor(e,t){this.name=n.SERVER_OPENING,this.topologyId=e,this.address=t}},t.ServerClosedEvent=class{constructor(e,t){this.name=n.SERVER_CLOSED,this.topologyId=e,this.address=t}},t.TopologyDescriptionChangedEvent=class{constructor(e,t,o){this.name=n.TOPOLOGY_DESCRIPTION_CHANGED,this.topologyId=e,this.previousDescription=t,this.newDescription=o}},t.TopologyOpeningEvent=class{constructor(e){this.name=n.TOPOLOGY_OPENING,this.topologyId=e}},t.TopologyClosedEvent=class{constructor(e){this.name=n.TOPOLOGY_CLOSED,this.topologyId=e}},t.ServerHeartbeatStartedEvent=class{constructor(e,t){this.name=n.SERVER_HEARTBEAT_STARTED,this.connectionId=e,this.awaited=t}},t.ServerHeartbeatSucceededEvent=class{constructor(e,t,o,r){this.name=n.SERVER_HEARTBEAT_SUCCEEDED,this.connectionId=e,this.duration=t,this.reply=o??{},this.awaited=r}},t.ServerHeartbeatFailedEvent=class{constructor(e,t,o,r){this.name=n.SERVER_HEARTBEAT_FAILED,this.connectionId=e,this.duration=t,this.failure=o,this.awaited=r}}},86552:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ReadConcern=t.ReadConcernLevel=void 0,t.ReadConcernLevel=Object.freeze({local:"local",majority:"majority",linearizable:"linearizable",available:"available",snapshot:"snapshot"});class o{constructor(e){this.level=t.ReadConcernLevel[e]??e}static fromOptions(e){if(null!=e){if(e.readConcern){const{readConcern:t}=e;if(t instanceof o)return t;if("string"==typeof t)return new o(t);if("level"in t&&t.level)return new o(t.level)}return e.level?new o(e.level):void 0}}static get MAJORITY(){return t.ReadConcernLevel.majority}static get AVAILABLE(){return t.ReadConcernLevel.available}static get LINEARIZABLE(){return t.ReadConcernLevel.linearizable}static get SNAPSHOT(){return t.ReadConcernLevel.snapshot}toJSON(){return{level:this.level}}}t.ReadConcern=o},86675:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DropSearchIndexOperation=void 0;const n=o(72216),r=o(36997),i=o(28947);class s extends i.AbstractOperation{constructor(e,t){super(),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.collection=e,this.name=t,this.ns=e.fullNamespace}get commandName(){return"dropSearchIndex"}buildCommand(e,t){const o={dropSearchIndex:this.collection.fullNamespace.collection};return"string"==typeof this.name&&(o.name=this.name),o}handleOk(e){}buildOptions(e){return{session:this.session,timeoutContext:e}}handleError(e){if(!(e instanceof r.MongoServerError&&e.code===r.MONGODB_ERROR_CODES.NamespaceNotFound))throw e}}t.DropSearchIndexOperation=s},87187:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AutomatedCallbackWorkflow=void 0;const n=o(36997),r=o(33628),i=o(41720),s=o(50558);class a extends s.CallbackWorkflow{constructor(e,t){super(e,t)}async execute(e,t){if(this.cache.hasAccessToken){const o=this.cache.getAccessToken();e.accessToken||(e.accessToken=o);try{return await this.finishAuthentication(e,t,o)}catch(o){if(o instanceof n.MongoError&&o.code===n.MONGODB_ERROR_CODES.AuthenticationFailed)return this.cache.removeAccessToken(),await this.execute(e,t);throw o}}const o=await this.fetchAccessToken(t);this.cache.put(o),e.accessToken=o.accessToken,await this.finishAuthentication(e,t,o.accessToken)}async fetchAccessToken(e){const t=new AbortController,o={timeoutContext:t.signal,version:i.OIDC_VERSION};e.username&&(o.username=e.username),e.mechanismProperties.TOKEN_RESOURCE&&(o.tokenAudience=e.mechanismProperties.TOKEN_RESOURCE);const a=r.Timeout.expires(s.AUTOMATED_TIMEOUT_MS);try{return await Promise.race([this.executeAndValidateCallback(o),a])}catch(e){if(r.TimeoutError.is(e))throw t.abort(),new n.MongoOIDCError(`OIDC callback timed out after ${s.AUTOMATED_TIMEOUT_MS}ms.`);throw e}finally{a.clear()}}}t.AutomatedCallbackWorkflow=a},87192:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.GetMoreOperation=void 0;const n=o(72216),r=o(36997),i=o(30306),s=o(28947);class a extends s.AbstractOperation{constructor(e,t,o,r){super(r),this.SERVER_COMMAND_RESPONSE_TYPE=n.CursorResponse,this.options=r,this.ns=e,this.cursorId=t,this.server=o}get commandName(){return"getMore"}buildCommand(e){if(null==this.cursorId||this.cursorId.isZero())throw new r.MongoRuntimeError("Unable to iterate cursor with no id");const t=this.ns.collection;if(null==t)throw new r.MongoRuntimeError("A collection name must be determined before getMore");const o={getMore:this.cursorId,collection:t};return"number"==typeof this.options.batchSize&&(o.batchSize=Math.abs(this.options.batchSize)),"number"==typeof this.options.maxAwaitTimeMS&&(o.maxTimeMS=this.options.maxAwaitTimeMS),void 0!==this.options.comment&&(0,i.maxWireVersion)(e)>=9&&(o.comment=this.options.comment),o}buildOptions(e){return{returnFieldSelector:null,documentsReturnedIn:"nextBatch",timeoutContext:e,...this.options}}handleOk(e){return e}}t.GetMoreOperation=a,(0,s.defineAspects)(a,[s.Aspect.READ_OPERATION,s.Aspect.MUST_SELECT_SAME_SERVER])},87535:(e,t,o)=>{var n=o(34110).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.OpCompressedRequest=t.OpMsgResponse=t.OpMsgRequest=t.DocumentSequence=t.OpReply=t.OpQueryRequest=void 0;const r=o(77953),i=o(36997),s=o(73738),a=o(60889);let c=0;const l=r.BSON.onDemand.ByteUtils.encodeUTF8Into;class d{constructor(e,t,o){this.moreToCome=!1;const n=`${e}.$cmd`;if("string"!=typeof e)throw new i.MongoRuntimeError("Database name must be a string for a query");if(null==t)throw new i.MongoRuntimeError("A query document must be specified for query");if(-1!==n.indexOf("\0"))throw new i.MongoRuntimeError("Namespace cannot contain a null character");this.databaseName=e,this.query=t,this.ns=n,this.numberToSkip=o.numberToSkip||0,this.numberToReturn=o.numberToReturn||0,this.returnFieldSelector=o.returnFieldSelector||void 0,this.requestId=o.requestId??d.getRequestId(),this.pre32Limit=o.pre32Limit,this.serializeFunctions="boolean"==typeof o.serializeFunctions&&o.serializeFunctions,this.ignoreUndefined="boolean"==typeof o.ignoreUndefined&&o.ignoreUndefined,this.maxBsonSize=o.maxBsonSize||16777216,this.checkKeys="boolean"==typeof o.checkKeys&&o.checkKeys,this.batchSize=this.numberToReturn,this.tailable=!1,this.secondaryOk="boolean"==typeof o.secondaryOk&&o.secondaryOk,this.oplogReplay=!1,this.noCursorTimeout=!1,this.awaitData=!1,this.exhaust=!1,this.partial=!1}incRequestId(){this.requestId=c++}nextRequestId(){return c+1}static getRequestId(){return++c}toBin(){const e=[];let t=null,o=0;this.tailable&&(o|=2),this.secondaryOk&&(o|=4),this.oplogReplay&&(o|=8),this.noCursorTimeout&&(o|=16),this.awaitData&&(o|=32),this.exhaust&&(o|=64),this.partial&&(o|=128),this.batchSize!==this.numberToReturn&&(this.numberToReturn=this.batchSize);const i=n.alloc(20+n.byteLength(this.ns)+1+4+4);e.push(i);const s=r.serialize(this.query,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined});e.push(s),this.returnFieldSelector&&Object.keys(this.returnFieldSelector).length>0&&(t=r.serialize(this.returnFieldSelector,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined}),e.push(t));const c=i.length+s.length+(t?t.length:0);let l=4;return i[3]=c>>24&255,i[2]=c>>16&255,i[1]=c>>8&255,i[0]=255&c,i[l+3]=this.requestId>>24&255,i[l+2]=this.requestId>>16&255,i[l+1]=this.requestId>>8&255,i[l]=255&this.requestId,l+=4,i[l+3]=0,i[l+2]=0,i[l+1]=0,i[l]=0,l+=4,i[l+3]=a.OP_QUERY>>24&255,i[l+2]=a.OP_QUERY>>16&255,i[l+1]=a.OP_QUERY>>8&255,i[l]=255&a.OP_QUERY,l+=4,i[l+3]=o>>24&255,i[l+2]=o>>16&255,i[l+1]=o>>8&255,i[l]=255&o,l+=4,l=l+i.write(this.ns,l,"utf8")+1,i[l-1]=0,i[l+3]=this.numberToSkip>>24&255,i[l+2]=this.numberToSkip>>16&255,i[l+1]=this.numberToSkip>>8&255,i[l]=255&this.numberToSkip,l+=4,i[l+3]=this.numberToReturn>>24&255,i[l+2]=this.numberToReturn>>16&255,i[l+1]=this.numberToReturn>>8&255,i[l]=255&this.numberToReturn,l+=4,e}}t.OpQueryRequest=d,t.OpReply=class{constructor(e,t,o,n){this.index=0,this.sections=[],this.moreToCome=!1,this.parsed=!1,this.raw=e,this.data=o,this.opts=n??{useBigInt64:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1},this.length=t.length,this.requestId=t.requestId,this.responseTo=t.responseTo,this.opCode=t.opCode,this.fromCompressed=t.fromCompressed,this.useBigInt64="boolean"==typeof this.opts.useBigInt64&&this.opts.useBigInt64,this.promoteLongs="boolean"!=typeof this.opts.promoteLongs||this.opts.promoteLongs,this.promoteValues="boolean"!=typeof this.opts.promoteValues||this.opts.promoteValues,this.promoteBuffers="boolean"==typeof this.opts.promoteBuffers&&this.opts.promoteBuffers,this.bsonRegExp="boolean"==typeof this.opts.bsonRegExp&&this.opts.bsonRegExp}isParsed(){return this.parsed}parse(){if(this.parsed)return this.sections[0];if(this.index=20,this.responseFlags=this.data.readInt32LE(0),this.cursorId=new r.Long(this.data.readInt32LE(4),this.data.readInt32LE(8)),this.startingFrom=this.data.readInt32LE(12),this.numberReturned=this.data.readInt32LE(16),this.numberReturned<0||this.numberReturned>2**32-1)throw new RangeError(`OP_REPLY numberReturned is an invalid array length ${this.numberReturned}`);this.cursorNotFound=!!(1&this.responseFlags),this.queryFailure=!!(2&this.responseFlags),this.shardConfigStale=!!(4&this.responseFlags),this.awaitCapable=!!(8&this.responseFlags);for(let e=0;e<this.numberReturned;e++){const e=this.data[this.index]|this.data[this.index+1]<<8|this.data[this.index+2]<<16|this.data[this.index+3]<<24,t=this.data.subarray(this.index,this.index+e);this.sections.push(t),this.index=this.index+e}return this.parsed=!0,this.sections[0]}};class u{constructor(e,t){this.field=e,this.documents=[],this.chunks=[],this.serializedDocumentsLength=0;const o=n.allocUnsafe(5+this.field.length+1);if(o[0]=1,l(o,`${this.field}\0`,5),this.chunks.push(o),this.header=o,t)for(const e of t)this.push(e,r.serialize(e))}push(e,t){return this.serializedDocumentsLength+=t.length,this.documents.push(e),this.chunks.push(t),this.header?.writeInt32LE(4+this.field.length+1+this.serializedDocumentsLength,1),this.serializedDocumentsLength+this.header.length}toBin(){return n.concat(this.chunks)}}t.DocumentSequence=u;class h{constructor(e,t,o){if(null==t)throw new i.MongoInvalidArgumentError("Query document must be specified for query");this.databaseName=e,this.command=t,this.command.$db=e,this.options=o??{},this.requestId=o.requestId?o.requestId:h.getRequestId(),this.serializeFunctions="boolean"==typeof o.serializeFunctions&&o.serializeFunctions,this.ignoreUndefined="boolean"==typeof o.ignoreUndefined&&o.ignoreUndefined,this.checkKeys="boolean"==typeof o.checkKeys&&o.checkKeys,this.maxBsonSize=o.maxBsonSize||16777216,this.checksumPresent=!1,this.moreToCome=o.moreToCome??0===t.writeConcern?.w,this.exhaustAllowed="boolean"==typeof o.exhaustAllowed&&o.exhaustAllowed}toBin(){const e=[];let t=0;this.checksumPresent&&(t|=1),this.moreToCome&&(t|=2),this.exhaustAllowed&&(t|=65536);const o=n.alloc(20);e.push(o);let r=o.length;const i=this.command;return r+=this.makeSections(e,i),o.writeInt32LE(r,0),o.writeInt32LE(this.requestId,4),o.writeInt32LE(0,8),o.writeInt32LE(a.OP_MSG,12),o.writeUInt32LE(t,16),e}makeSections(e,t){const o=this.extractDocumentSequences(t),r=n.allocUnsafe(1);r[0]=0;const i=this.serializeBson(t);return e.push(r),e.push(i),e.push(o),r.length+i.length+o.length}extractDocumentSequences(e){const t=[];for(const[o,n]of Object.entries(e))n instanceof u&&(t.push(n.toBin()),delete e[o]);return t.length>0?n.concat(t):n.alloc(0)}serializeBson(e){return r.serialize(e,{checkKeys:this.checkKeys,serializeFunctions:this.serializeFunctions,ignoreUndefined:this.ignoreUndefined})}static getRequestId(){return c=c+1&2147483647,c}}t.OpMsgRequest=h,t.OpMsgResponse=class{constructor(e,t,o,n){this.index=0,this.sections=[],this.parsed=!1,this.raw=e,this.data=o,this.opts=n??{useBigInt64:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!1,bsonRegExp:!1},this.length=t.length,this.requestId=t.requestId,this.responseTo=t.responseTo,this.opCode=t.opCode,this.fromCompressed=t.fromCompressed,this.responseFlags=o.readInt32LE(0),this.checksumPresent=!!(1&this.responseFlags),this.moreToCome=!!(2&this.responseFlags),this.exhaustAllowed=!!(65536&this.responseFlags),this.useBigInt64="boolean"==typeof this.opts.useBigInt64&&this.opts.useBigInt64,this.promoteLongs="boolean"!=typeof this.opts.promoteLongs||this.opts.promoteLongs,this.promoteValues="boolean"!=typeof this.opts.promoteValues||this.opts.promoteValues,this.promoteBuffers="boolean"==typeof this.opts.promoteBuffers&&this.opts.promoteBuffers,this.bsonRegExp="boolean"==typeof this.opts.bsonRegExp&&this.opts.bsonRegExp}isParsed(){return this.parsed}parse(){if(this.parsed)return this.sections[0];for(this.index=4;this.index<this.data.length;){const e=this.data.readUInt8(this.index++);if(0===e){const e=this.data.readUInt32LE(this.index),t=this.data.subarray(this.index,this.index+e);this.sections.push(t),this.index+=e}else if(1===e)throw new i.MongoRuntimeError("OP_MSG Payload Type 1 detected unsupported protocol")}return this.parsed=!0,this.sections[0]}},t.OpCompressedRequest=class{constructor(e,t){this.command=e,this.options={zlibCompressionLevel:t.zlibCompressionLevel,agreedCompressor:t.agreedCompressor}}static canCompress(e){const t=e instanceof h?e.command:e.query,o=Object.keys(t)[0];return!s.uncompressibleCommands.has(o)}async toBin(){const e=n.concat(this.command.toBin()),t=e.slice(16),o=e.readInt32LE(12),r=await(0,s.compress)(this.options,t),i=n.alloc(16);i.writeInt32LE(25+r.length,0),i.writeInt32LE(this.command.requestId,4),i.writeInt32LE(0,8),i.writeInt32LE(a.OP_COMPRESSED,12);const c=n.alloc(9);return c.writeInt32LE(o,0),c.writeInt32LE(t.length,4),c.writeUInt8(s.Compressor[this.options.agreedCompressor],8),[i,c,r]}}},88e3:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.KillCursorsOperation=void 0;const n=o(72216),r=o(36997),i=o(28947);class s extends i.AbstractOperation{constructor(e,t,o,r){super(r),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.ns=t,this.cursorId=e,this.server=o}get commandName(){return"killCursors"}buildCommand(e,t){const o=this.ns.collection;if(null==o)throw new r.MongoRuntimeError("A collection name must be determined before killCursors");return{killCursors:o,cursors:[this.cursorId]}}buildOptions(e){return{session:this.session,timeoutContext:e}}handleError(e){}}t.KillCursorsOperation=s,(0,i.defineAspects)(s,[i.Aspect.MUST_SELECT_SAME_SERVER])},88757:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MongoClient=t.ServerApiVersion=void 0;const n=o(4308),r=o(183),i=o(77953),s=o(53373),a=o(32985),c=o(65070),l=o(84778),d=o(52859),u=o(34842),h=o(3137),m=o(36997),p=o(30427),g=o(60866),f=o(72361),S=o(2560),E=o(93055),y=o(39131),b=o(74891),O=o(26119),C=o(36964),M=o(86098),T=o(30306);t.ServerApiVersion=Object.freeze({v1:"1"});class w extends f.TypedEventEmitter{constructor(e,t){super(),this.driverInfoList=[],this.on("error",T.noop),this.options=(0,d.parseOptions)(e,this,t),this.appendMetadata(this.options.driverInfo);const o=Object.values(this.options.mongoLoggerOptions.componentSeverities).some((e=>e!==g.SeverityLevel.OFF));this.mongoLogger=o?new g.MongoLogger(this.options.mongoLoggerOptions):void 0;const n=this;this.s={url:e,bsonOptions:(0,i.resolveBSONOptions)(this.options),namespace:(0,T.ns)("admin"),hasBeenClosed:!1,sessionPool:new M.ServerSessionPool(this),activeSessions:new Set,activeCursors:new Set,authProviders:new p.MongoClientAuthProviders,get options(){return n.options},get readConcern(){return n.options.readConcern},get writeConcern(){return n.options.writeConcern},get readPreference(){return n.options.readPreference},get isMongoClient(){return!0}},this.checkForNonGenuineHosts()}async[Symbol.asyncDispose](){await this.close()}appendMetadata(e){this.driverInfoList.some((t=>(0,l.isDriverInfoEqual)(t,e)))||(this.driverInfoList.push(e),this.options.metadata=(0,l.makeClientMetadata)(this.driverInfoList,this.options).then(void 0,T.squashError).then((e=>e??{})))}checkForNonGenuineHosts(){const e=this.options.hosts.filter((e=>(0,T.isHostMatch)(T.DOCUMENT_DB_CHECK,e.host))),t=(0,T.isHostMatch)(T.DOCUMENT_DB_CHECK,this.options.srvHost),o=this.options.hosts.filter((e=>(0,T.isHostMatch)(T.COSMOS_DB_CHECK,e.host))),n=(0,T.isHostMatch)(T.COSMOS_DB_CHECK,this.options.srvHost);0!==e.length||t?this.mongoLogger?.info("client",T.DOCUMENT_DB_MSG):(0!==o.length||n)&&this.mongoLogger?.info("client",T.COSMOS_DB_MSG)}get serverApi(){return this.options.serverApi&&Object.freeze({...this.options.serverApi})}get monitorCommands(){return this.options.monitorCommands}set monitorCommands(e){this.options.monitorCommands=e}get autoEncrypter(){return this.options.autoEncrypter}get readConcern(){return this.s.readConcern}get writeConcern(){return this.s.writeConcern}get readPreference(){return this.s.readPreference}get bsonOptions(){return this.s.bsonOptions}get timeoutMS(){return this.s.options.timeoutMS}async bulkWrite(e,t){if(this.autoEncrypter)throw new m.MongoInvalidArgumentError("MongoClient bulkWrite does not currently support automatic encryption.");return await new S.ClientBulkWriteExecutor(this,e,(0,T.resolveOptions)(this,t)).execute()}async connect(){if(this.connectionLock)return await this.connectionLock;try{this.connectionLock=this._connect(),await this.connectionLock}finally{this.connectionLock=void 0}return this}async _connect(){if(this.topology&&this.topology.isConnected())return this;const e=this.options;if(e.tls&&("string"==typeof e.tlsCAFile&&(e.ca??=await n.promises.readFile(e.tlsCAFile)),"string"==typeof e.tlsCRLFile&&(e.crl??=await n.promises.readFile(e.tlsCRLFile)),!("string"!=typeof e.tlsCertificateKeyFile||e.key&&e.cert))){const t=await n.promises.readFile(e.tlsCertificateKeyFile);e.key??=t,e.cert??=t}if("string"==typeof e.srvHost){const t=await(0,d.resolveSRVRecord)(e);for(const[o,n]of t.entries())e.hosts[o]=n}if(e.credentials?.mechanism===c.AuthMechanism.MONGODB_OIDC){const t=e.credentials?.mechanismProperties?.ALLOWED_HOSTS||a.DEFAULT_ALLOWED_HOSTS;if(!e.credentials?.mechanismProperties?.ENVIRONMENT)for(const o of e.hosts)if(!(0,T.hostMatchesWildcards)(o.toHostPort().host,t))throw new m.MongoInvalidArgumentError(`Host '${o}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${t.join(",")}'`)}this.topology=new C.Topology(this,e.hosts,e),this.topology.once(C.Topology.OPEN,(()=>this.emit("open",this)));for(const e of u.MONGO_CLIENT_EVENTS)this.topology.on(e,((...t)=>this.emit(e,...t)));const t=async()=>{try{await(this.topology?.connect(e))}catch(e){throw this.topology?.close(),e}};return this.autoEncrypter?(await(this.autoEncrypter?.init()),await t(),await e.encrypter.connectInternalClient()):await t(),this}async close(e=!1){if(this.closeLock)return await this.closeLock;try{this.closeLock=this._close(),await this.closeLock}finally{this.closeLock=void 0}}async _close(){Object.defineProperty(this.s,"hasBeenClosed",{value:!0,enumerable:!0,configurable:!1,writable:!1}),this.topology?.closeCheckedOutConnections();const e=Array.from(this.s.activeCursors,(e=>e.close()));this.s.activeCursors.clear(),await Promise.all(e);const t=Array.from(this.s.activeSessions,(e=>e.endSession()));if(this.s.activeSessions.clear(),await Promise.all(t),null==this.topology)return;(this.topology.description.type===r.TopologyType.LoadBalanced||null!=this.topology.description.logicalSessionTimeoutMinutes)&&await async function(e,{description:t}){const o=(0,O.readPreferenceServerSelector)(b.ReadPreference.primaryPreferred),n=Array.from(t.servers.values());if(0!==o(t,n,new O.DeprioritizedServers).length){const t=Array.from(e.s.sessionPool.sessions,(({id:e})=>e));if(0!==t.length)try{await(0,y.executeOperation)(e,new E.EndSessionsOperation(t))}catch(e){(0,T.squashError)(e)}}}(this,this.topology);const o=this.topology;this.topology=void 0,o.close();const{encrypter:n}=this.options;n&&await n.close(this)}db(e,t){t=t??{},e||(e=this.s.options.dbName);const o=Object.assign({},this.options,t);return new h.Db(this,e,o)}static async connect(e,t){const o=new this(e,t);return await o.connect()}startSession(e){const t=new M.ClientSession(this,this.s.sessionPool,{explicit:!0,...e},this.options);return this.s.activeSessions.add(t),t.once("ended",(()=>{this.s.activeSessions.delete(t)})),t}async withSession(e,t){const o={owner:Symbol(),..."object"==typeof e?e:{}},n="function"==typeof e?e:t;if(null==n)throw new m.MongoInvalidArgumentError("Missing required callback parameter");const r=this.startSession(o);try{return await n(r)}finally{try{await r.endSession()}catch(e){(0,T.squashError)(e)}}}watch(e=[],t={}){return Array.isArray(e)||(t=e,e=[]),new s.ChangeStream(this,e,(0,T.resolveOptions)(this,t))}}t.MongoClient=w},89678:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Server=void 0;const n=o(23121),r=o(90202),i=o(17502),s=o(34842),a=o(36997),c=o(72361),l=o(86065),d=o(67518),u=o(30306),h=o(71259),m=o(90648),p=o(93323),g=o(32583),f=o(26119),S=(0,u.makeStateMachine)({[m.STATE_CLOSED]:[m.STATE_CLOSED,m.STATE_CONNECTING],[m.STATE_CONNECTING]:[m.STATE_CONNECTING,m.STATE_CLOSING,m.STATE_CONNECTED,m.STATE_CLOSED],[m.STATE_CONNECTED]:[m.STATE_CONNECTED,m.STATE_CLOSING,m.STATE_CLOSED],[m.STATE_CLOSING]:[m.STATE_CLOSING,m.STATE_CLOSED]});class E extends c.TypedEventEmitter{static{this.SERVER_HEARTBEAT_STARTED=s.SERVER_HEARTBEAT_STARTED}static{this.SERVER_HEARTBEAT_SUCCEEDED=s.SERVER_HEARTBEAT_SUCCEEDED}static{this.SERVER_HEARTBEAT_FAILED=s.SERVER_HEARTBEAT_FAILED}static{this.CONNECT=s.CONNECT}static{this.DESCRIPTION_RECEIVED=s.DESCRIPTION_RECEIVED}static{this.CLOSED=s.CLOSED}static{this.ENDED=s.ENDED}constructor(e,t,o){super(),this.on("error",u.noop),this.serverApi=o.serverApi;const i={hostAddress:t.hostAddress,...o};this.topology=e,this.pool=new r.ConnectionPool(this,i),this.s={description:t,options:o,state:m.STATE_CLOSED,operationCount:0};for(const e of[...s.CMAP_EVENTS,...s.APM_EVENTS])this.pool.on(e,(t=>this.emit(e,t)));if(this.pool.on(n.Connection.CLUSTER_TIME_RECEIVED,(e=>{this.clusterTime=e})),this.loadBalanced)this.monitor=null;else{this.monitor=new p.Monitor(this,this.s.options);for(const e of s.HEARTBEAT_EVENTS)this.monitor.on(e,(t=>this.emit(e,t)));this.monitor.on("resetServer",(e=>y(this,e))),this.monitor.on(E.SERVER_HEARTBEAT_SUCCEEDED,(e=>{this.emit(E.DESCRIPTION_RECEIVED,new g.ServerDescription(this.description.hostAddress,e.reply,{roundTripTime:this.monitor?.roundTripTime,minRoundTripTime:this.monitor?.minRoundTripTime})),this.s.state===m.STATE_CONNECTING&&(S(this,m.STATE_CONNECTED),this.emit(E.CONNECT,this))}))}}get clusterTime(){return this.topology.clusterTime}set clusterTime(e){this.topology.clusterTime=e}get description(){return this.s.description}get name(){return this.s.description.address}get autoEncrypter(){if(this.s.options&&this.s.options.autoEncrypter)return this.s.options.autoEncrypter}get loadBalanced(){return this.topology.description.type===m.TopologyType.LoadBalanced}connect(){this.s.state===m.STATE_CLOSED&&(S(this,m.STATE_CONNECTING),this.loadBalanced?(S(this,m.STATE_CONNECTED),this.emit(E.CONNECT,this)):this.monitor?.connect())}closeCheckedOutConnections(){return this.pool.closeCheckedOutConnections()}close(){this.s.state!==m.STATE_CLOSED&&(S(this,m.STATE_CLOSING),this.loadBalanced||this.monitor?.close(),this.pool.close(),S(this,m.STATE_CLOSED),this.emit("closed"))}requestCheck(){this.loadBalanced||this.monitor?.requestCheck()}async command(e,t){if(this.s.state===m.STATE_CLOSING||this.s.state===m.STATE_CLOSED)throw new a.MongoServerClosedError;const o=e.session;let n=o?.pinnedConnection;if(this.incrementOperationCount(),null==n)try{n=await this.pool.checkOut({timeoutContext:t,signal:e.options.signal})}catch(e){throw this.decrementOperationCount(),e instanceof i.PoolClearedError||this.handleError(e),e}let r=null;const s=()=>{if(this.decrementOperationCount(),o?.pinnedConnection!==n)if(null!=r){const e=()=>{this.pool.checkIn(n)};r.then(e,e)}else this.pool.checkIn(n)};let c;try{c=e.buildCommand(n,o)}catch(e){throw s(),e}const d=e.buildOptions(t),p=e.ns;this.loadBalanced&&function(e,t){return!!t&&(t.inTransaction()||t.transaction.isCommitted&&"commitTransaction"in e||"aggregate"in e||"find"in e||"getMore"in e||"listCollections"in e||"listIndexes"in e||"bulkWrite"in e)}(c,o)&&!o?.pinnedConnection&&o?.pin(n),d.directConnection=this.topology.s.options.directConnection,e instanceof l.AggregateOperation&&e.hasWriteStage&&(0,u.maxWireVersion)(n)<f.MIN_SECONDARY_WRITE_WIRE_VERSION&&delete d.readPreference,this.description.iscryptd&&(d.omitMaxTimeMS=!0);try{try{const t=await n.command(p,c,d,e.SERVER_COMMAND_RESPONSE_TYPE);return(0,h.throwIfWriteConcernError)(t),t}catch(e){throw this.decorateCommandError(n,c,d,e)}}catch(t){if(!(t instanceof a.MongoError&&t.code?.valueOf()===a.MONGODB_ERROR_CODES.Reauthenticate))throw t;r=this.pool.reauthenticate(n),r.then(void 0,(e=>{r=null,(0,u.squashError)(e)})),await(0,u.abortable)(r,d),r=null;try{const t=await n.command(p,c,d,e.SERVER_COMMAND_RESPONSE_TYPE);return(0,h.throwIfWriteConcernError)(t),t}catch(e){throw this.decorateCommandError(n,c,d,e)}}finally{s()}}handleError(e,t){if(!(e instanceof a.MongoError))return;if(function(e,t){const o=e.pool.generation,n=t.connectionGeneration;if(n&&n<o)return!0;const r=e.description.topologyVersion;return(0,g.compareTopologyVersion)(r,t.topologyVersion)>=0}(this,e))return;const o=e instanceof a.MongoNetworkError&&!(e instanceof a.MongoNetworkTimeoutError),n=e instanceof a.MongoNetworkError&&e.beforeHandshake,r=e.hasErrorLabel(a.MongoErrorLabel.HandshakeError),i=e.hasErrorLabel(a.MongoErrorLabel.SystemOverloadedError);if((0,a.isStateChangeError)(e)||e instanceof a.MongoParseError){const o=(0,a.isNodeShuttingDownError)(e);if(!this.loadBalanced)return o&&e.addErrorLabel(a.MongoErrorLabel.ResetPool),y(this,e),void queueMicrotask((()=>this.requestCheck()));t&&o&&this.pool.clear({serviceId:t.serviceId})}else if(o||n||r){if(i)return;this.loadBalanced?t&&this.pool.clear({serviceId:t.serviceId}):(e.addErrorLabel(a.MongoErrorLabel.ResetPool),y(this,e))}}decorateCommandError(e,t,o,n){if("object"!=typeof n||null==n||!("name"in n))throw new a.MongoRuntimeError("An unexpected error type: "+typeof n);if("AbortError"===n.name&&"cause"in n&&n.cause instanceof a.MongoError&&(n=n.cause),!(n instanceof a.MongoError))return n;if(function(e,t){return t.serviceId?t.generation!==e.serviceGenerations.get(t.serviceId.toHexString()):t.generation!==e.generation}(this.pool,e))return n;const r=o?.session;return n instanceof a.MongoNetworkError?(r&&!r.hasEnded&&r.serverSession&&(r.serverSession.isDirty=!0),b(r,t)&&!n.hasErrorLabel(a.MongoErrorLabel.TransientTransactionError)&&n.addErrorLabel(a.MongoErrorLabel.TransientTransactionError),(O(this.topology)||(0,d.isTransactionCommand)(t))&&(0,u.supportsRetryableWrites)(this)&&!b(r,t)&&n.addErrorLabel(a.MongoErrorLabel.RetryableWriteError)):(O(this.topology)||(0,d.isTransactionCommand)(t))&&(0,a.needsRetryableWriteLabel)(n,(0,u.maxWireVersion)(this),this.description.type)&&!b(r,t)&&n.addErrorLabel(a.MongoErrorLabel.RetryableWriteError),r&&r.isPinned&&n.hasErrorLabel(a.MongoErrorLabel.TransientTransactionError)&&r.unpin({force:!0}),this.handleError(n,e),n}decrementOperationCount(){return this.s.operationCount-=1}incrementOperationCount(){return this.s.operationCount+=1}}function y(e,t){e.loadBalanced||(t instanceof a.MongoNetworkError&&!(t instanceof a.MongoNetworkTimeoutError)&&e.monitor?.reset(),e.emit(E.DESCRIPTION_RECEIVED,new g.ServerDescription(e.description.hostAddress,void 0,{error:t})))}function b(e,t){return e&&e.inTransaction()&&!(0,d.isTransactionCommand)(t)}function O(e){return!1!==e.s.options.retryWrites}t.Server=E},90202:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionPool=t.PoolState=void 0;const n=o(31713),r=o(34842),i=o(36997),s=o(72361),a=o(33628),c=o(30306),l=o(97159),d=o(23121),u=o(78948),h=o(17502),m=o(67204);t.PoolState=Object.freeze({paused:"paused",ready:"ready",closed:"closed"});class p extends s.TypedEventEmitter{static{this.CONNECTION_POOL_CREATED=r.CONNECTION_POOL_CREATED}static{this.CONNECTION_POOL_CLOSED=r.CONNECTION_POOL_CLOSED}static{this.CONNECTION_POOL_CLEARED=r.CONNECTION_POOL_CLEARED}static{this.CONNECTION_POOL_READY=r.CONNECTION_POOL_READY}static{this.CONNECTION_CREATED=r.CONNECTION_CREATED}static{this.CONNECTION_READY=r.CONNECTION_READY}static{this.CONNECTION_CLOSED=r.CONNECTION_CLOSED}static{this.CONNECTION_CHECK_OUT_STARTED=r.CONNECTION_CHECK_OUT_STARTED}static{this.CONNECTION_CHECK_OUT_FAILED=r.CONNECTION_CHECK_OUT_FAILED}static{this.CONNECTION_CHECKED_OUT=r.CONNECTION_CHECKED_OUT}static{this.CONNECTION_CHECKED_IN=r.CONNECTION_CHECKED_IN}constructor(e,o){if(super(),this.on("error",c.noop),this.options=Object.freeze({connectionType:d.Connection,...o,maxPoolSize:o.maxPoolSize??100,minPoolSize:o.minPoolSize??0,maxConnecting:o.maxConnecting??2,maxIdleTimeMS:o.maxIdleTimeMS??0,waitQueueTimeoutMS:o.waitQueueTimeoutMS??0,minPoolSizeCheckFrequencyMS:o.minPoolSizeCheckFrequencyMS??100,autoEncrypter:o.autoEncrypter}),this.options.minPoolSize>this.options.maxPoolSize)throw new i.MongoInvalidArgumentError("Connection pool minimum size must not be greater than maximum pool size");this.poolState=t.PoolState.paused,this.server=e,this.connections=new c.List,this.pending=0,this.checkedOut=new Set,this.minPoolSizeTimer=void 0,this.generation=0,this.serviceGenerations=new Map,this.connectionCounter=(0,c.makeCounter)(1),this.cancellationToken=new s.CancellationToken,this.cancellationToken.setMaxListeners(1/0),this.waitQueue=new c.List,this.metrics=new m.ConnectionPoolMetrics,this.processingWaitQueue=!1,this.mongoLogger=this.server.topology.client?.mongoLogger,this.component="connection",queueMicrotask((()=>{this.emitAndLog(p.CONNECTION_POOL_CREATED,new u.ConnectionPoolCreatedEvent(this))}))}get address(){return this.options.hostAddress.toString()}get closed(){return this.poolState===t.PoolState.closed}get totalConnectionCount(){return this.availableConnectionCount+this.pendingConnectionCount+this.currentCheckedOutCount}get availableConnectionCount(){return this.connections.length}get pendingConnectionCount(){return this.pending}get currentCheckedOutCount(){return this.checkedOut.size}get waitQueueSize(){return this.waitQueue.length}get loadBalanced(){return this.options.loadBalanced}get serverError(){return this.server.description.error}get checkedOutConnections(){return this.checkedOut}waitQueueErrorMetrics(){return this.metrics.info(this.options.maxPoolSize)}ready(){this.poolState===t.PoolState.paused&&(this.poolState=t.PoolState.ready,this.emitAndLog(p.CONNECTION_POOL_READY,new u.ConnectionPoolReadyEvent(this)),(0,n.clearTimeout)(this.minPoolSizeTimer),this.ensureMinPoolSize())}async checkOut(e){const t=(0,c.processTimeMS)();this.emitAndLog(p.CONNECTION_CHECK_OUT_STARTED,new u.ConnectionCheckOutStartedEvent(this));const{promise:o,resolve:n,reject:r}=(0,c.promiseWithResolvers)(),s=e.timeoutContext.connectionCheckoutTimeout,l={resolve:n,reject:r,cancelled:!1,checkoutTime:t},d=(0,c.addAbortListener)(e.signal,(function(){l.cancelled=!0,r(this.reason)}));this.waitQueue.push(l),queueMicrotask((()=>this.processWaitQueue()));try{return s?.throwIfExpired(),await(s?Promise.race([o,s]):o)}catch(t){if(a.TimeoutError.is(t)){s?.clear(),l.cancelled=!0,this.emitAndLog(p.CONNECTION_CHECK_OUT_FAILED,new u.ConnectionCheckOutFailedEvent(this,"timeout",l.checkoutTime));const t=new h.WaitQueueTimeoutError(this.loadBalanced?this.waitQueueErrorMetrics():"Timed out while checking out a connection from connection pool",this.address);if(e.timeoutContext.csotEnabled())throw new i.MongoOperationTimeoutError("Timed out during connection checkout",{cause:t});throw t}throw t}finally{d?.[c.kDispose](),s?.clear()}}checkIn(e){if(!this.checkedOut.has(e))return;const t=this.closed,o=this.connectionIsStale(e),n=!!(t||o||e.closed);if(n||(e.markAvailable(),this.connections.unshift(e)),this.checkedOut.delete(e),this.emitAndLog(p.CONNECTION_CHECKED_IN,new u.ConnectionCheckedInEvent(this,e)),n){const o=e.closed?"error":t?"poolClosed":"stale";this.destroyConnection(e,o)}queueMicrotask((()=>this.processWaitQueue()))}clear(e={}){if(this.closed)return;if(this.loadBalanced){const{serviceId:t}=e;if(!t)throw new i.MongoRuntimeError("ConnectionPool.clear() called in load balanced mode with no serviceId.");const o=t.toHexString(),n=this.serviceGenerations.get(o);if(null==n)throw new i.MongoRuntimeError("Service generations are required in load balancer mode.");return this.serviceGenerations.set(o,n+1),void this.emitAndLog(p.CONNECTION_POOL_CLEARED,new u.ConnectionPoolClearedEvent(this,{serviceId:t}))}const o=e.interruptInUseConnections??!1,n=this.generation;this.generation+=1;const r=this.poolState===t.PoolState.paused;this.poolState=t.PoolState.paused,this.clearMinPoolSizeTimer(),r||this.emitAndLog(p.CONNECTION_POOL_CLEARED,new u.ConnectionPoolClearedEvent(this,{interruptInUseConnections:o})),o&&queueMicrotask((()=>this.interruptInUseConnections(n))),this.processWaitQueue()}interruptInUseConnections(e){for(const t of this.checkedOut)t.generation<=e&&t.onError(new h.PoolClearedOnNetworkError(this))}closeCheckedOutConnections(){for(const e of this.checkedOut)e.onError(new i.MongoClientClosedError)}close(){if(!this.closed){this.cancellationToken.emit("cancel"),"function"==typeof this.connectionCounter.return&&this.connectionCounter.return(void 0),this.poolState=t.PoolState.closed,this.clearMinPoolSizeTimer(),this.processWaitQueue();for(const e of this.connections)this.emitAndLog(p.CONNECTION_CLOSED,new u.ConnectionClosedEvent(this,e,"poolClosed")),e.destroy();this.connections.clear(),this.emitAndLog(p.CONNECTION_POOL_CLOSED,new u.ConnectionPoolClosedEvent(this))}}async reauthenticate(e){const t=e.authContext;if(!t)throw new i.MongoRuntimeError("No auth context found on connection.");const o=t.credentials;if(!o)throw new i.MongoMissingCredentialsError("Connection is missing credentials when asked to reauthenticate");const n=o.resolveAuthMechanism(e.hello),r=this.server.topology.client.s.authProviders.getOrCreateProvider(n.mechanism,n.mechanismProperties);if(!r)throw new i.MongoMissingCredentialsError(`Reauthenticate failed due to no auth provider for ${o.mechanism}`);await r.reauth(t)}clearMinPoolSizeTimer(){const e=this.minPoolSizeTimer;e&&(0,n.clearTimeout)(e)}destroyConnection(e,t){this.emitAndLog(p.CONNECTION_CLOSED,new u.ConnectionClosedEvent(this,e,t)),e.destroy()}connectionIsStale(e){const t=e.serviceId;if(this.loadBalanced&&t){const o=t.toHexString(),n=this.serviceGenerations.get(o);return e.generation!==n}return e.generation!==this.generation}connectionIsIdle(e){return!!(this.options.maxIdleTimeMS&&e.idleTime>this.options.maxIdleTimeMS)}destroyConnectionIfPerished(e){const t=this.connectionIsStale(e),o=this.connectionIsIdle(e);if(!t&&!o&&!e.closed)return!1;const n=e.closed?"error":t?"stale":"idle";return this.destroyConnection(e,n),!0}createConnection(e){const o={...this.options,id:this.connectionCounter.next().value,generation:this.generation,cancellationToken:this.cancellationToken,mongoLogger:this.mongoLogger,authProviders:this.server.topology.client.s.authProviders,metadata:this.server.topology.client.options.metadata};this.pending++;const n=(0,c.processTimeMS)();this.emitAndLog(p.CONNECTION_CREATED,new u.ConnectionCreatedEvent(this,{id:o.id})),(0,l.connect)(o).then((o=>{if(this.poolState!==t.PoolState.ready)return this.pending--,o.destroy(),void e(this.closed?new h.PoolClosedError(this):new h.PoolClearedError(this));for(const e of[...r.APM_EVENTS,d.Connection.CLUSTER_TIME_RECEIVED])o.on(e,(t=>this.emit(e,t)));if(this.loadBalanced){o.on(d.Connection.PINNED,(e=>this.metrics.markPinned(e))),o.on(d.Connection.UNPINNED,(e=>this.metrics.markUnpinned(e)));const e=o.serviceId;if(e){let t;const n=e.toHexString();(t=this.serviceGenerations.get(n))?o.generation=t:(this.serviceGenerations.set(n,0),o.generation=0)}}o.markAvailable(),this.emitAndLog(p.CONNECTION_READY,new u.ConnectionReadyEvent(this,o,n)),this.pending--,e(void 0,o)}),(t=>{this.pending--,this.server.handleError(t),this.emitAndLog(p.CONNECTION_CLOSED,new u.ConnectionClosedEvent(this,{id:o.id,serviceId:void 0},"error",t)),(t instanceof i.MongoNetworkError||t instanceof i.MongoServerError)&&(t.connectionGeneration=o.generation),e(t??new i.MongoRuntimeError("Connection creation failed without error"))}))}ensureMinPoolSize(){const e=this.options.minPoolSize;this.poolState===t.PoolState.ready&&(this.connections.prune((e=>this.destroyConnectionIfPerished(e))),this.totalConnectionCount<e&&this.pendingConnectionCount<this.options.maxConnecting?this.createConnection(((e,o)=>{!e&&o&&(this.connections.push(o),queueMicrotask((()=>this.processWaitQueue()))),this.poolState===t.PoolState.ready&&((0,n.clearTimeout)(this.minPoolSizeTimer),this.minPoolSizeTimer=(0,n.setTimeout)((()=>this.ensureMinPoolSize()),this.options.minPoolSizeCheckFrequencyMS))})):((0,n.clearTimeout)(this.minPoolSizeTimer),this.minPoolSizeTimer=(0,n.setTimeout)((()=>this.ensureMinPoolSize()),this.options.minPoolSizeCheckFrequencyMS)))}processWaitQueue(){if(this.processingWaitQueue)return;for(this.processingWaitQueue=!0;this.waitQueueSize;){const e=this.waitQueue.first();if(!e){this.waitQueue.shift();continue}if(e.cancelled){this.waitQueue.shift();continue}if(this.poolState!==t.PoolState.ready){const t=this.closed?"poolClosed":"connectionError",o=this.closed?new h.PoolClosedError(this):new h.PoolClearedError(this);this.emitAndLog(p.CONNECTION_CHECK_OUT_FAILED,new u.ConnectionCheckOutFailedEvent(this,t,e.checkoutTime,o)),this.waitQueue.shift(),e.reject(o);continue}if(!this.availableConnectionCount)break;const o=this.connections.shift();if(!o)break;this.destroyConnectionIfPerished(o)||(this.checkedOut.add(o),this.emitAndLog(p.CONNECTION_CHECKED_OUT,new u.ConnectionCheckedOutEvent(this,o,e.checkoutTime)),this.waitQueue.shift(),e.resolve(o))}const{maxPoolSize:e,maxConnecting:o}=this.options;for(;this.waitQueueSize>0&&this.pendingConnectionCount<o&&(0===e||this.totalConnectionCount<e);){const e=this.waitQueue.shift();e&&!e.cancelled&&this.createConnection(((t,o)=>{e.cancelled?!t&&o&&this.connections.push(o):t?(this.emitAndLog(p.CONNECTION_CHECK_OUT_FAILED,new u.ConnectionCheckOutFailedEvent(this,"connectionError",e.checkoutTime,t)),e.reject(t)):o&&(this.checkedOut.add(o),this.emitAndLog(p.CONNECTION_CHECKED_OUT,new u.ConnectionCheckedOutEvent(this,o,e.checkoutTime)),e.resolve(o)),queueMicrotask((()=>this.processWaitQueue()))}))}this.processingWaitQueue=!1}}t.ConnectionPool=p},90648:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServerType=t.TopologyType=t.STATE_CONNECTED=t.STATE_CONNECTING=t.STATE_CLOSED=t.STATE_CLOSING=void 0,t._advanceClusterTime=function(e,t){(null==e.clusterTime||t.clusterTime.greaterThan(e.clusterTime.clusterTime))&&(e.clusterTime=t)},t.STATE_CLOSING="closing",t.STATE_CLOSED="closed",t.STATE_CONNECTING="connecting",t.STATE_CONNECTED="connected",t.TopologyType=Object.freeze({Single:"Single",ReplicaSetNoPrimary:"ReplicaSetNoPrimary",ReplicaSetWithPrimary:"ReplicaSetWithPrimary",Sharded:"Sharded",Unknown:"Unknown",LoadBalanced:"LoadBalanced"}),t.ServerType=Object.freeze({Standalone:"Standalone",Mongos:"Mongos",PossiblePrimary:"PossiblePrimary",RSPrimary:"RSPrimary",RSSecondary:"RSSecondary",RSArbiter:"RSArbiter",RSOther:"RSOther",RSGhost:"RSGhost",Unknown:"Unknown",LoadBalancer:"LoadBalancer"})},91200:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.buildReplaceOneOperation=t.buildUpdateManyOperation=t.buildUpdateOneOperation=t.buildDeleteManyOperation=t.buildDeleteOneOperation=t.buildInsertOneOperation=t.ClientBulkWriteCommandBuilder=void 0,t.buildOperation=u;const n=o(77953),r=o(87535),i=o(36997),s=o(24007),a=o(30306);function c(e,t,o){if(t.length>o)throw new i.MongoInvalidArgumentError(`Client bulk write operation ${e} of length ${t.length} exceeds the max bson object size of ${o}`)}function l(e,t,o){const n={delete:t,multi:o,filter:e.filter};return e.hint&&(n.hint=e.hint),e.collation&&(n.collation=e.collation),n}function d(e,t,o,n){!function(e,t){if(!(0,a.hasAtomicOperators)(e,t))throw new i.MongoAPIError("Client bulk write update models must only contain atomic modifiers (start with $) and must not be empty.")}(e.update,n);const r={update:t,multi:o,filter:e.filter,updateMods:e.update};return e.hint&&(r.hint=e.hint),e.upsert&&(r.upsert=e.upsert),e.arrayFilters&&(r.arrayFilters=e.arrayFilters),e.collation&&(r.collation=e.collation),!o&&"sort"in e&&null!=e.sort&&(r.sort=(0,s.formatSort)(e.sort)),r}function u(e,o,n,r){switch(e.name){case"insertOne":return(0,t.buildInsertOneOperation)(e,o,n);case"deleteOne":return(0,t.buildDeleteOneOperation)(e,o);case"deleteMany":return(0,t.buildDeleteManyOperation)(e,o);case"updateOne":return(0,t.buildUpdateOneOperation)(e,o,r);case"updateMany":return(0,t.buildUpdateManyOperation)(e,o,r);case"replaceOne":return(0,t.buildReplaceOneOperation)(e,o)}}t.ClientBulkWriteCommandBuilder=class{constructor(e,t,o){this.models=e,this.options=t,this.pkFactory=o??a.DEFAULT_PK_FACTORY,this.currentModelIndex=0,this.previousModelIndex=0,this.lastOperations=[],this.isBatchRetryable=!0}get errorsOnly(){return!("verboseResults"in this.options)||!this.options.verboseResults}hasNextBatch(){return this.currentModelIndex<this.models.length}resetBatch(){return this.currentModelIndex=this.previousModelIndex,!0}buildBatch(e,t,o){this.isBatchRetryable=!0;let r=0,s=0;const a=this.baseCommand(),l=new Map;for(this.previousModelIndex=this.currentModelIndex;this.currentModelIndex<this.models.length;){const d=this.models[this.currentModelIndex],h=d.namespace,m=l.get(h);if("deleteMany"!==d.name&&"updateMany"!==d.name||(this.isBatchRetryable=!1),null!=m){const s=u(d,m,this.pkFactory,this.options);let l;try{l=n.BSON.serialize(s)}catch(e){throw new i.MongoInvalidArgumentError("Could not serialize operation to BSON",{cause:e})}if(c("ops",l,o),!(r+l.length<e&&a.ops.documents.length<t))break;r=1e3+a.ops.push(s,l),this.currentModelIndex++}else{l.set(h,s);const m={ns:h},p=u(d,s,this.pkFactory,this.options);let g,f;try{g=n.BSON.serialize(m),f=n.BSON.serialize(p)}catch(e){throw new i.MongoInvalidArgumentError("Could not serialize ns info to BSON",{cause:e})}if(c("nsInfo",g,o),c("ops",f,o),!(r+g.length+f.length<e&&a.ops.documents.length<t))break;r=1e3+a.nsInfo.push(m,g)+a.ops.push(p,f),s++,this.currentModelIndex++}}return this.lastOperations=a.ops.documents,a}baseCommand(){const e={bulkWrite:1,errorsOnly:this.errorsOnly,ordered:this.options.ordered??!0,ops:new r.DocumentSequence("ops"),nsInfo:new r.DocumentSequence("nsInfo")};return null!=this.options.bypassDocumentValidation&&(e.bypassDocumentValidation=this.options.bypassDocumentValidation),this.options.let&&(e.let=this.options.let),void 0!==this.options.comment&&(e.comment=this.options.comment),e}},t.buildInsertOneOperation=(e,t,o)=>{const n={insert:t,document:e.document};return n.document._id=e.document._id??o.createPk(),n},t.buildDeleteOneOperation=(e,t)=>l(e,t,!1),t.buildDeleteManyOperation=(e,t)=>l(e,t,!0),t.buildUpdateOneOperation=(e,t,o)=>d(e,t,!1,o),t.buildUpdateManyOperation=(e,t,o)=>d(e,t,!0,o),t.buildReplaceOneOperation=(e,t)=>{if((0,a.hasAtomicOperators)(e.replacement))throw new i.MongoAPIError("Client bulk write replace models must not contain atomic modifiers (start with $) and must not be empty.");const o={update:t,multi:!1,filter:e.filter,updateMods:e.replacement};return e.hint&&(o.hint=e.hint),e.upsert&&(o.upsert=e.upsert),e.collation&&(o.collation=e.collation),null!=e.sort&&(o.sort=(0,s.formatSort)(e.sort)),o}},92294:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CreateSearchIndexesOperation=void 0;const n=o(72216),r=o(28947);class i extends r.AbstractOperation{constructor(e,t){super(),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.collection=e,this.descriptions=t,this.ns=e.fullNamespace}get commandName(){return"createSearchIndexes"}buildCommand(e,t){return{createSearchIndexes:this.collection.fullNamespace.collection,indexes:this.descriptions}}handleOk(e){return super.handleOk(e).indexesCreated.map((e=>e.name))}buildOptions(e){return{session:this.session,timeoutContext:e}}}t.CreateSearchIndexesOperation=i},92762:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CommonErrors=t.MongoshCommandFailed=t.MongoshDeprecatedError=t.MongoshUnimplementedError=t.MongoshInvalidInputError=t.MongoshInternalError=t.MongoshRuntimeError=t.MongoshWarning=t.MongoshBaseError=void 0,t.getScopeFromErrorCode=r,t.isShouldReportAsBugError=function(e){return e?.code===n.CommonErrors.UnexpectedInternalError};const n=o(94985);function r(e){if(!e)return;const t=/^([a-zA-Z0-9]+)-/.exec(e);return t?t[1]:void 0}Object.defineProperty(t,"CommonErrors",{enumerable:!0,get:function(){return n.CommonErrors}});class i extends Error{constructor(e,t,o,n){super(o?`[${o}] ${t}`:t),this.name=e,this.code=o,this.scope=r(o),this.metadata=n}}t.MongoshBaseError=i,t.MongoshRuntimeError=class extends i{constructor(e,t,o){super("MongoshRuntimeError",e,t,o)}},t.MongoshInternalError=class extends i{constructor(e,t){super("MongoshInternalError",e,n.CommonErrors.UnexpectedInternalError,t)}},t.MongoshUnimplementedError=class extends i{constructor(e,t,o){super("MongoshUnimplementedError",e,t,o)}},t.MongoshInvalidInputError=class extends i{constructor(e,t,o){super("MongoshInvalidInputError",e,t,o)}},t.MongoshWarning=class extends i{constructor(e,t,o){super("MongoshWarning",e,t,o)}},t.MongoshDeprecatedError=class extends i{constructor(e,t){super("MongoshDeprecatedError",e,n.CommonErrors.Deprecated,t)}},t.MongoshCommandFailed=class extends i{constructor(e,t){super("MongoshCommandFailed",`Command ${e} returned ok: 0. To see the raw results of the command, use 'runCommand' instead.`,n.CommonErrors.CommandFailed,t)}}},93055:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EndSessionsOperation=void 0;const n=o(72216),r=o(41539),i=o(74891),s=o(30306),a=o(28947);class c extends r.CommandOperation{constructor(e){super(),this.writeConcern={w:0},this.ns=s.MongoDBNamespace.fromString("admin.$cmd"),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.sessions=e}buildCommandDocument(e,t){return{endSessions:this.sessions}}buildOptions(e){return{timeoutContext:e,readPreference:i.ReadPreference.primaryPreferred}}get commandName(){return"endSessions"}}t.EndSessionsOperation=c,(0,a.defineAspects)(c,a.Aspect.WRITE_OPERATION)},93323:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RTTSampler=t.MonitorInterval=t.RTTPinger=t.Monitor=t.ServerMonitoringMode=void 0;const n=o(31713),r=o(77953),i=o(97159),s=o(84778),a=o(34842),c=o(36997),l=o(60866),d=o(72361),u=o(30306),h=o(90648),m=o(86348),p=o(89678),g="idle",f="monitoring",S=(0,u.makeStateMachine)({[h.STATE_CLOSING]:[h.STATE_CLOSING,g,h.STATE_CLOSED],[h.STATE_CLOSED]:[h.STATE_CLOSED,f],[g]:[g,f,h.STATE_CLOSING],[f]:[f,g,h.STATE_CLOSING]}),E=new Set([h.STATE_CLOSING,h.STATE_CLOSED,f]);function y(e){return e.s.state===h.STATE_CLOSED||e.s.state===h.STATE_CLOSING}t.ServerMonitoringMode=Object.freeze({auto:"auto",poll:"poll",stream:"stream"});class b extends d.TypedEventEmitter{constructor(e,t){super(),this.component=l.MongoLoggableComponent.TOPOLOGY,this.on("error",u.noop),this.server=e,this.connection=null,this.cancellationToken=new d.CancellationToken,this.cancellationToken.setMaxListeners(1/0),this.monitorId=void 0,this.s={state:h.STATE_CLOSED},this.address=e.description.address,this.options=Object.freeze({connectTimeoutMS:t.connectTimeoutMS??1e4,heartbeatFrequencyMS:t.heartbeatFrequencyMS??1e4,minHeartbeatFrequencyMS:t.minHeartbeatFrequencyMS??500,serverMonitoringMode:t.serverMonitoringMode}),this.isRunningInFaasEnv=null!=(0,s.getFAASEnv)(),this.mongoLogger=this.server.topology.client?.mongoLogger,this.rttSampler=new v(10);const o=this.cancellationToken,n={id:"<monitor>",generation:e.pool.generation,cancellationToken:o,hostAddress:e.description.hostAddress,...t,raw:!1,useBigInt64:!1,promoteLongs:!0,promoteValues:!0,promoteBuffers:!0};delete n.credentials,n.autoEncrypter&&delete n.autoEncrypter,this.connectOptions=Object.freeze(n)}connect(){if(this.s.state!==h.STATE_CLOSED)return;const e=this.options.heartbeatFrequencyMS,t=this.options.minHeartbeatFrequencyMS;this.monitorId=new w(M(this),{heartbeatFrequencyMS:e,minHeartbeatFrequencyMS:t,immediate:!0})}requestCheck(){E.has(this.s.state)||this.monitorId?.wake()}reset(){const e=this.server.description.topologyVersion;if(y(this)||null==e)return;S(this,h.STATE_CLOSING),O(this),S(this,g);const t=this.options.heartbeatFrequencyMS,o=this.options.minHeartbeatFrequencyMS;this.monitorId=new w(M(this),{heartbeatFrequencyMS:t,minHeartbeatFrequencyMS:o})}close(){y(this)||(S(this,h.STATE_CLOSING),O(this),this.emit("close"),S(this,h.STATE_CLOSED))}get roundTripTime(){return this.rttSampler.average()}get minRoundTripTime(){return this.rttSampler.min()}get latestRtt(){return this.rttSampler.last}addRttSample(e){this.rttSampler.addSample(e)}clearRttSamples(){this.rttSampler.clear()}}function O(e){e.monitorId?.stop(),e.monitorId=void 0,e.rttPinger?.close(),e.rttPinger=void 0,e.cancellationToken.emit("cancel"),e.connection?.destroy(),e.connection=null,e.clearRttSamples()}function C(e,o){if(null==o)return!1;const n=e.options.serverMonitoringMode;return n!==t.ServerMonitoringMode.poll&&(n===t.ServerMonitoringMode.stream||!e.isRunningInFaasEnv)}function M(e){return t=>{function o(){y(e)||S(e,g),t()}e.s.state!==f?(S(e,f),function(e,t){let o,n;const s=e.server.description.topologyVersion,l=C(e,s);function d(r){e.connection?.destroy(),e.connection=null,e.emitAndLogHeartbeat(p.Server.SERVER_HEARTBEAT_FAILED,e.server.topology.s.id,void 0,new m.ServerHeartbeatFailedEvent(e.address,(0,u.calculateDurationInMs)(o),r,n));const i=r instanceof c.MongoError?r:new c.MongoError(c.MongoError.buildErrorMessage(r),{cause:r});i.addErrorLabel(c.MongoErrorLabel.ResetPool),i instanceof c.MongoNetworkTimeoutError&&i.addErrorLabel(c.MongoErrorLabel.InterruptInUseConnections),e.emit("resetServer",i),t(r)}function h(n){"isWritablePrimary"in n||(n.isWritablePrimary=n[a.LEGACY_HELLO_COMMAND]);const r=l&&e.rttPinger?e.rttPinger.latestRtt??(0,u.calculateDurationInMs)(o):(0,u.calculateDurationInMs)(o);e.addRttSample(r),e.emitAndLogHeartbeat(p.Server.SERVER_HEARTBEAT_SUCCEEDED,e.server.topology.s.id,n.connectionId,new m.ServerHeartbeatSucceededEvent(e.address,r,n,l)),l?(e.emitAndLogHeartbeat(p.Server.SERVER_HEARTBEAT_STARTED,e.server.topology.s.id,void 0,new m.ServerHeartbeatStartedEvent(e.address,!0)),o=(0,u.processTimeMS)()):(e.rttPinger?.close(),e.rttPinger=void 0,t(void 0,n))}e.emitAndLogHeartbeat(p.Server.SERVER_HEARTBEAT_STARTED,e.server.topology.s.id,void 0,new m.ServerHeartbeatStartedEvent(e.address,l));const{connection:g}=e;if(g&&!g.closed){const{serverApi:t,helloOk:i}=g,c=e.options.connectTimeoutMS,m=e.options.heartbeatFrequencyMS,p={[t?.version||i?"hello":a.LEGACY_HELLO_COMMAND]:1,...l&&s?{maxAwaitTimeMS:m,topologyVersion:(f=s,{processId:f.processId,counter:r.Long.isLong(f.counter)?f.counter:r.Long.fromNumber(f.counter)})}:{}},S=l?{socketTimeoutMS:c?c+m:0,exhaustAllowed:!0}:{socketTimeoutMS:c};return l&&null==e.rttPinger&&(e.rttPinger=new T(e)),o=(0,u.processTimeMS)(),l?(n=!0,g.exhaustCommand((0,u.ns)("admin.$cmd"),p,S,((e,t)=>e?d(e):h(t)))):(n=!1,void g.command((0,u.ns)("admin.$cmd"),p,S).then(h,d))}var f;(async()=>{const t=await(0,i.makeSocket)(e.connectOptions),n=(0,i.makeConnection)(e.connectOptions,t);o=(0,u.processTimeMS)();try{return await(0,i.performInitialHandshake)(n,e.connectOptions),n}catch(e){throw n.destroy(),e}})().then((n=>{if(y(e))return void n.destroy();const r=(0,u.calculateDurationInMs)(o);e.addRttSample(r),e.connection=n,e.emitAndLogHeartbeat(p.Server.SERVER_HEARTBEAT_SUCCEEDED,e.server.topology.s.id,n.hello?.connectionId,new m.ServerHeartbeatSucceededEvent(e.address,r,n.hello,C(e,n.hello?.topologyVersion))),t(void 0,n.hello)}),(t=>{e.connection=null,n=!1,d(t)}))}(e,((t,r)=>{if(t&&e.server.description.type===h.ServerType.Unknown)return o();C(e,r?.topologyVersion)&&(0,n.setTimeout)((()=>{y(e)||e.monitorId?.wake()}),0),o()}))):queueMicrotask(t)}}t.Monitor=b;class T{constructor(e){this.connection=void 0,this.cancellationToken=e.cancellationToken,this.closed=!1,this.monitor=e,this.latestRtt=e.latestRtt??void 0;const t=e.options.heartbeatFrequencyMS;this.monitorId=(0,n.setTimeout)((()=>this.measureRoundTripTime()),t)}get roundTripTime(){return this.monitor.roundTripTime}get minRoundTripTime(){return this.monitor.minRoundTripTime}close(){this.closed=!0,(0,n.clearTimeout)(this.monitorId),this.connection?.destroy(),this.connection=void 0}measureAndReschedule(e,t){this.closed?t?.destroy():(null==this.connection&&(this.connection=t),this.latestRtt=(0,u.calculateDurationInMs)(e),this.monitorId=(0,n.setTimeout)((()=>this.measureRoundTripTime()),this.monitor.options.heartbeatFrequencyMS))}measureRoundTripTime(){const e=(0,u.processTimeMS)();if(this.closed)return;const t=this.connection;if(null==t)return void(0,i.connect)(this.monitor.connectOptions).then((t=>{this.measureAndReschedule(e,t)}),(()=>{this.connection=void 0}));const o=t.serverApi?.version||t.helloOk?"hello":a.LEGACY_HELLO_COMMAND;t.command((0,u.ns)("admin.$cmd"),{[o]:1},void 0).then((()=>this.measureAndReschedule(e)),(()=>{this.connection?.destroy(),this.connection=void 0}))}}t.RTTPinger=T;class w{constructor(e,t={}){this.isExpeditedCallToFnScheduled=!1,this.stopped=!1,this.isExecutionInProgress=!1,this.hasExecutedOnce=!1,this._executeAndReschedule=()=>{this.stopped||(this.timerId&&(0,n.clearTimeout)(this.timerId),this.isExpeditedCallToFnScheduled=!1,this.isExecutionInProgress=!0,this.fn((()=>{this.lastExecutionEnded=(0,u.processTimeMS)(),this.isExecutionInProgress=!1,this._reschedule(this.heartbeatFrequencyMS)})))},this.fn=e,this.lastExecutionEnded=-1/0,this.heartbeatFrequencyMS=t.heartbeatFrequencyMS??1e3,this.minHeartbeatFrequencyMS=t.minHeartbeatFrequencyMS??500,t.immediate?this._executeAndReschedule():this._reschedule(void 0)}wake(){const e=(0,u.processTimeMS)()-this.lastExecutionEnded;return e<0?this._executeAndReschedule():this.isExecutionInProgress||this.isExpeditedCallToFnScheduled?void 0:e<this.minHeartbeatFrequencyMS?(this.isExpeditedCallToFnScheduled=!0,void this._reschedule(this.minHeartbeatFrequencyMS-e)):void this._executeAndReschedule()}stop(){this.stopped=!0,this.timerId&&((0,n.clearTimeout)(this.timerId),this.timerId=void 0),this.lastExecutionEnded=-1/0,this.isExpeditedCallToFnScheduled=!1}toString(){return JSON.stringify(this)}toJSON(){const e=(0,u.processTimeMS)(),t=e-this.lastExecutionEnded;return{timerId:null!=this.timerId?"set":"cleared",lastCallTime:this.lastExecutionEnded,isExpeditedCheckScheduled:this.isExpeditedCallToFnScheduled,stopped:this.stopped,heartbeatFrequencyMS:this.heartbeatFrequencyMS,minHeartbeatFrequencyMS:this.minHeartbeatFrequencyMS,currentTime:e,timeSinceLastCall:t}}_reschedule(e){this.stopped||(this.timerId&&(0,n.clearTimeout)(this.timerId),this.timerId=(0,n.setTimeout)(this._executeAndReschedule,e||this.heartbeatFrequencyMS))}}t.MonitorInterval=w;class v{constructor(e=10){this.rttSamples=new Float64Array(e),this.length=0,this.writeIndex=0}addSample(e){this.rttSamples[this.writeIndex++]=e,this.length<this.rttSamples.length&&this.length++,this.writeIndex%=this.rttSamples.length}min(){if(this.length<2)return 0;let e=this.rttSamples[0];for(let t=1;t<this.length;t++)this.rttSamples[t]<e&&(e=this.rttSamples[t]);return e}average(){if(0===this.length)return 0;let e=0;for(let t=0;t<this.length;t++)e+=this.rttSamples[t];return e/this.length}get last(){return 0===this.length?null:this.rttSamples[0===this.writeIndex?this.length-1:this.writeIndex-1]}clear(){this.length=0,this.writeIndex=0}}t.RTTSampler=v},93361:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},94289:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ListSearchIndexesCursor=void 0;const n=o(13237);class r extends n.AggregationCursor{constructor({fullNamespace:e,client:t},o,n={}){super(t,e,null==o?[{$listSearchIndexes:{}}]:[{$listSearchIndexes:{name:o}}],n)}}t.ListSearchIndexesCursor=r},94985:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CommonErrors=void 0,t.CommonErrors={InvalidArgument:"COMMON-10001",InvalidOperation:"COMMON-10002",Deprecated:"COMMON-10003",CommandFailed:"COMMON-10004",UnexpectedInternalError:"COMMON-90001",NotImplemented:"COMMON-90002"}},95157:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProfilingLevelOperation=void 0;const n=o(77953),r=o(72216),i=o(36997),s=o(41539);class a extends r.MongoDBResponse{get was(){return this.get("was",n.BSONType.int,!0)}}class c extends s.CommandOperation{constructor(e,t){super(e,t),this.SERVER_COMMAND_RESPONSE_TYPE=a,this.options=t}get commandName(){return"profile"}buildCommandDocument(e){return{profile:-1}}handleOk(e){if(1===e.ok){const t=e.was;if(0===t)return"off";if(1===t)return"slow_only";if(2===t)return"all";throw new i.MongoUnexpectedServerResponseError(`Illegal profiling level value ${t}`)}throw new i.MongoUnexpectedServerResponseError("Error with profile command")}}t.ProfilingLevelOperation=c},95174:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FindOneAndUpdateOperation=t.FindOneAndReplaceOperation=t.FindOneAndDeleteOperation=t.FindAndModifyOperation=t.ReturnDocument=void 0;const n=o(72216),r=o(36997),i=o(74891),s=o(24007),a=o(30306),c=o(41539),l=o(28947);function d(e,o){return e.new=o.returnDocument===t.ReturnDocument.AFTER,e.upsert=!0===o.upsert,!0===o.bypassDocumentValidation&&(e.bypassDocumentValidation=o.bypassDocumentValidation),e}t.ReturnDocument=Object.freeze({BEFORE:"before",AFTER:"after"});class u extends c.CommandOperation{constructor(e,t,o){super(e,o),this.SERVER_COMMAND_RESPONSE_TYPE=n.MongoDBResponse,this.options=o,this.readPreference=i.ReadPreference.primary,this.collection=e,this.query=t}get commandName(){return"findAndModify"}buildCommandDocument(e,t){const o=this.options,n={findAndModify:this.collection.collectionName,query:this.query,remove:!1,new:!1,upsert:!1};o.includeResultMetadata??=!1;const i=(0,s.formatSort)(o.sort);if(i&&(n.sort=i),o.projection&&(n.fields=o.projection),o.maxTimeMS&&(n.maxTimeMS=o.maxTimeMS),o.writeConcern&&(n.writeConcern=o.writeConcern),o.let&&(n.let=o.let),void 0!==o.comment&&(n.comment=o.comment),(0,a.decorateWithCollation)(n,o),o.hint){if(0===this.writeConcern?.w&&(0,a.maxWireVersion)(e)<9)throw new r.MongoCompatibilityError("hint for the findAndModify command is only supported on MongoDB 4.4+");n.hint=o.hint}return n}handleOk(e){const t=super.handleOk(e);return this.options.includeResultMetadata?t:t.value??null}}t.FindAndModifyOperation=u,t.FindOneAndDeleteOperation=class extends u{constructor(e,t,o){if(null==t||"object"!=typeof t)throw new r.MongoInvalidArgumentError('Argument "filter" must be an object');super(e,t,o)}buildCommandDocument(e,t){const o=super.buildCommandDocument(e,t);return o.remove=!0,o}},t.FindOneAndReplaceOperation=class extends u{constructor(e,t,o,n){if(null==t||"object"!=typeof t)throw new r.MongoInvalidArgumentError('Argument "filter" must be an object');if(null==o||"object"!=typeof o)throw new r.MongoInvalidArgumentError('Argument "replacement" must be an object');if((0,a.hasAtomicOperators)(o))throw new r.MongoInvalidArgumentError("Replacement document must not contain atomic operators");super(e,t,n),this.replacement=o}buildCommandDocument(e,t){const o=super.buildCommandDocument(e,t);return o.update=this.replacement,d(o,this.options),o}},t.FindOneAndUpdateOperation=class extends u{constructor(e,t,o,n){if(null==t||"object"!=typeof t)throw new r.MongoInvalidArgumentError('Argument "filter" must be an object');if(null==o||"object"!=typeof o)throw new r.MongoInvalidArgumentError('Argument "update" must be an object');if(!(0,a.hasAtomicOperators)(o,n))throw new r.MongoInvalidArgumentError("Update document requires atomic operators");super(e,t,n),this.update=o,this.options=n}buildCommandDocument(e,t){const o=super.buildCommandDocument(e,t);return o.update=this.update,d(o,this.options),this.options.arrayFilters&&(o.arrayFilters=this.options.arrayFilters),o}},(0,l.defineAspects)(u,[l.Aspect.WRITE_OPERATION,l.Aspect.RETRYABLE,l.Aspect.EXPLAINABLE,l.Aspect.SUPPORTS_RAW_DATA])},96109:function(e,t,o){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const r=n(o(67415));t.default=new r.default},97159:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LEGAL_TCP_SOCKET_OPTIONS=t.LEGAL_TLS_SOCKET_OPTIONS=t.DEFAULT_KEEP_ALIVE_INITIAL_DELAY_MS=void 0,t.connect=async function(e){let t=null;try{return t=p(e,await E(e)),await g(t,e),t}catch(e){throw t?.destroy(),e}},t.makeConnection=p,t.performInitialHandshake=g,t.prepareHandshakeDocument=f,t.makeSocket=E;const n=o(51390),r=o(1568),i=o(34842),s=o(98517),a=o(36997),c=o(30306),l=o(68950),d=o(65070),u=o(23121),h=o(60889);function m(e){e.addErrorLabel(a.MongoErrorLabel.SystemOverloadedError),e.addErrorLabel(a.MongoErrorLabel.RetryableError)}function p(e,t){let o=e.connectionType??u.Connection;return e.autoEncrypter&&(o=u.CryptoConnection),new o(t,e)}async function g(e,t){const o=t.credentials;if(o&&o.mechanism!==d.AuthMechanism.MONGODB_DEFAULT&&!t.authProviders.getOrCreateProvider(o.mechanism,o.mechanismProperties))throw new a.MongoInvalidArgumentError(`AuthMechanism '${o.mechanism}' not supported`);const n=new l.AuthContext(e,o,t);e.authContext=n;const r=await f(n),s={...t,raw:!1};"number"==typeof t.connectTimeoutMS&&(s.socketTimeoutMS=t.connectTimeoutMS);const u=(new Date).getTime(),p=await async function(t,o){try{return await e.command((0,c.ns)("admin.$cmd"),t,o)}catch(e){throw e instanceof a.MongoError&&e.addErrorLabel(a.MongoErrorLabel.HandshakeError),e instanceof a.MongoNetworkError&&m(e),e}}(r,s);"isWritablePrimary"in p||(p.isWritablePrimary=p[i.LEGACY_HELLO_COMMAND]),p.helloOk&&(e.helloOk=!0);const g=function(e,t){const o=Number(e.maxWireVersion),n=Number(e.minWireVersion),r=!Number.isNaN(o)&&o>=h.MIN_SUPPORTED_WIRE_VERSION,i=!Number.isNaN(n)&&n<=h.MAX_SUPPORTED_WIRE_VERSION;if(r){if(i)return null;const o=`Server at ${t.hostAddress} reports minimum wire version ${JSON.stringify(e.minWireVersion)}, but this version of the Node.js Driver requires at most ${h.MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${h.MAX_SUPPORTED_SERVER_VERSION})`;return new a.MongoCompatibilityError(o)}const s=`Server at ${t.hostAddress} reports maximum wire version ${JSON.stringify(e.maxWireVersion)??0}, but this version of the Node.js Driver requires at least ${h.MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${h.MIN_SUPPORTED_SERVER_VERSION})`;return new a.MongoCompatibilityError(s)}(p,t);if(g)throw g;if(t.loadBalanced&&!p.serviceId)throw new a.MongoCompatibilityError("Driver attempted to initialize in load balancing mode, but the server does not support this mode.");if(e.hello=p,e.lastHelloMS=(new Date).getTime()-u,!p.arbiterOnly&&o){n.response=p;const r=o.resolveAuthMechanism(p),i=t.authProviders.getOrCreateProvider(r.mechanism,r.mechanismProperties);if(!i)throw new a.MongoInvalidArgumentError(`No AuthProvider for ${r.mechanism} defined.`);try{await i.auth(n)}catch(t){throw t instanceof a.MongoError&&(t.addErrorLabel(a.MongoErrorLabel.HandshakeError),(0,a.needsRetryableWriteLabel)(t,p.maxWireVersion,e.description.type)&&t.addErrorLabel(a.MongoErrorLabel.RetryableWriteError)),t}}e.established=!0}async function f(e){const t=e.options,o=t.compressors?t.compressors:[],{serverApi:n}=e.connection,r=await t.metadata,s={[n?.version||!0===t.loadBalanced?"hello":i.LEGACY_HELLO_COMMAND]:1,helloOk:!0,client:r,compression:o};!0===t.loadBalanced&&(s.loadBalanced=!0);const c=e.credentials;if(c){if(c.mechanism===d.AuthMechanism.MONGODB_DEFAULT&&c.username){s.saslSupportedMechs=`${c.source}.${c.username}`;const t=e.options.authProviders.getOrCreateProvider(d.AuthMechanism.MONGODB_SCRAM_SHA256,c.mechanismProperties);if(!t)throw new a.MongoInvalidArgumentError(`No AuthProvider for ${d.AuthMechanism.MONGODB_SCRAM_SHA256} defined.`);return await t.prepare(s,e)}const t=e.options.authProviders.getOrCreateProvider(c.mechanism,c.mechanismProperties);if(!t)throw new a.MongoInvalidArgumentError(`No AuthProvider for ${c.mechanism} defined.`);return await t.prepare(s,e)}return s}function S(e){const o=e.hostAddress;if(!o)throw new a.MongoInvalidArgumentError('Option "hostAddress" is required');const n={};for(const o of t.LEGAL_TCP_SOCKET_OPTIONS)null!=e[o]&&(n[o]=e[o]);if(n.keepAliveInitialDelay??=t.DEFAULT_KEEP_ALIVE_INITIAL_DELAY_MS,n.keepAlive=!0,n.noDelay=e.noDelay??!0,"string"==typeof o.socketPath)return n.path=o.socketPath,n;if("string"==typeof o.host)return n.host=o.host,n.port=o.port,n;throw new a.MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(o)}`)}async function E(e){const o=e.tls??!1,i=e.connectTimeoutMS??3e4,l=e.existingSocket,d=e.keepAliveInitialDelay??t.DEFAULT_KEEP_ALIVE_INITIAL_DELAY_MS,u=e.noDelay??!0;let h;if(null!=e.proxyHost)return await async function(e){const t=c.HostAddress.fromHostPort(e.proxyHost??"",e.proxyPort??1080),o=await E({...e,hostAddress:t,tls:!1,proxyHost:void 0}),n=S(e);if("string"!=typeof n.host||"number"!=typeof n.port)throw new a.MongoInvalidArgumentError("Can only make Socks5 connections to TCP hosts");let r;y??=function(){if(null==y){const e=(0,s.getSocks)();if("kModuleError"in e)throw e.kModuleError;y=e}return y}();try{r=(await y.SocksClient.createConnection({existing_socket:o,timeout:e.connectTimeoutMS,command:"connect",destination:{host:n.host,port:n.port},proxy:{host:"iLoveJavaScript",port:0,type:5,userId:e.proxyUsername||void 0,password:e.proxyPassword||void 0}})).socket}catch(e){throw new a.MongoNetworkError(a.MongoError.buildErrorMessage(e),{cause:e})}return await E({...e,existingSocket:r,proxyHost:void 0})}({...e,connectTimeoutMS:i});if(o){const o=r.connect(function(e){const o=S(e);for(const n of t.LEGAL_TLS_SOCKET_OPTIONS)null!=e[n]&&(o[n]=e[n]);return e.existingSocket&&(o.socket=e.existingSocket),null==o.servername&&o.host&&!n.isIP(o.host)&&(o.servername=o.host),o}(e));"function"==typeof o.disableRenegotiation&&o.disableRenegotiation(),h=o}else h=l||n.createConnection(S(e));h.setKeepAlive(!0,d),h.setNoDelay(u),h.setTimeout(i);let p=null;const{promise:g,resolve:f,reject:b}=(0,c.promiseWithResolvers)();if(l)f(h);else{const t=performance.now(),n=o?"secureConnect":"connect";h.once(n,(()=>f(h))).once("error",(e=>b(new a.MongoNetworkError(a.MongoError.buildErrorMessage(e),{cause:e})))).once("timeout",(()=>{b(new a.MongoNetworkTimeoutError(`Socket '${n}' timed out after ${performance.now()-t|0}ms (connectTimeoutMS: ${i})`))})).once("close",(()=>b(new a.MongoNetworkError(`Socket closed after ${performance.now()-t|0} during connection establishment`)))),null!=e.cancellationToken&&(p=()=>b(new a.MongoNetworkError("Socket connection establishment was cancelled after "+(performance.now()-t|0))),e.cancellationToken.once("cancel",p))}try{return h=await g,h}catch(e){throw m(e),h.destroy(),e}finally{h.setTimeout(0),null!=p&&e.cancellationToken?.removeListener("cancel",p)}}t.DEFAULT_KEEP_ALIVE_INITIAL_DELAY_MS=12e4,t.LEGAL_TLS_SOCKET_OPTIONS=["allowPartialTrustChain","ALPNProtocols","ca","cert","checkServerIdentity","ciphers","crl","ecdhCurve","key","minDHSize","passphrase","pfx","rejectUnauthorized","secureContext","secureProtocol","servername","session"],t.LEGAL_TCP_SOCKET_OPTIONS=["autoSelectFamily","autoSelectFamilyAttemptTimeout","keepAliveInitialDelay","family","hints","localAddress","localPort","lookup"];let y=null},98517:(e,t,o)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getKerberos=function(){let e;try{e=o(64113)}catch(t){e=r(new n.MongoMissingDependencyError("Optional module `kerberos` not found. Please install it to enable kerberos authentication",{cause:t,dependencyName:"kerberos"}))}return e},t.getZstdLibrary=function(){let e;try{e=o(64113)}catch(t){e=r(new n.MongoMissingDependencyError("Optional module `@mongodb-js/zstd` not found. Please install it to enable zstd compression",{cause:t,dependencyName:"zstd"}))}return e},t.getAwsCredentialProvider=function(){try{return o(64113)}catch(e){return r(new n.MongoMissingDependencyError("Optional module `@aws-sdk/credential-providers` not found. Please install it to enable getting aws credentials via the official sdk.",{cause:e,dependencyName:"@aws-sdk/credential-providers"}))}},t.getGcpMetadata=function(){try{return o(64113)}catch(e){return r(new n.MongoMissingDependencyError("Optional module `gcp-metadata` not found. Please install it to enable getting gcp credentials via the official sdk.",{cause:e,dependencyName:"gcp-metadata"}))}},t.getSnappy=function(){try{return o(64113)}catch(e){return{kModuleError:new n.MongoMissingDependencyError("Optional module `snappy` not found. Please install it to enable snappy compression",{cause:e,dependencyName:"snappy"})}}},t.getSocks=function(){try{return o(64113)}catch(e){return{kModuleError:new n.MongoMissingDependencyError("Optional module `socks` not found. Please install it to connections over a SOCKS5 proxy",{cause:e,dependencyName:"socks"})}}},t.getMongoDBClientEncryption=function(){let e=null;try{e=o(64113)}catch(e){return{kModuleError:new n.MongoMissingDependencyError("Optional module `mongodb-client-encryption` not found. Please install it to use auto encryption or ClientEncryption.",{cause:e,dependencyName:"mongodb-client-encryption"})}}return e};const n=o(36997);function r(e){return new Proxy(e?{kModuleError:e}:{},{get:(t,o)=>{if("kModuleError"===o)return e;throw e},set:()=>{throw e}})}}};