mongodb 6.20.0-dev.20251106.sha.696664cb → 6.21.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 (151) hide show
  1. package/README.md +11 -11
  2. package/lib/beta.d.ts +9229 -0
  3. package/lib/beta.js +21 -0
  4. package/lib/beta.js.map +1 -0
  5. package/lib/bulk/common.js +9 -7
  6. package/lib/bulk/common.js.map +1 -1
  7. package/lib/change_stream.js +38 -84
  8. package/lib/change_stream.js.map +1 -1
  9. package/lib/client-side-encryption/auto_encrypter.js +4 -2
  10. package/lib/client-side-encryption/auto_encrypter.js.map +1 -1
  11. package/lib/client-side-encryption/client_encryption.js +3 -2
  12. package/lib/client-side-encryption/client_encryption.js.map +1 -1
  13. package/lib/client-side-encryption/crypto_callbacks.js +81 -0
  14. package/lib/client-side-encryption/crypto_callbacks.js.map +1 -0
  15. package/lib/client-side-encryption/errors.js +1 -3
  16. package/lib/client-side-encryption/errors.js.map +1 -1
  17. package/lib/client-side-encryption/mongocryptd_manager.js +1 -1
  18. package/lib/client-side-encryption/mongocryptd_manager.js.map +1 -1
  19. package/lib/cmap/auth/aws_temporary_credentials.js +58 -10
  20. package/lib/cmap/auth/aws_temporary_credentials.js.map +1 -1
  21. package/lib/cmap/auth/mongo_credentials.js +15 -0
  22. package/lib/cmap/auth/mongo_credentials.js.map +1 -1
  23. package/lib/cmap/auth/mongodb_aws.js +7 -2
  24. package/lib/cmap/auth/mongodb_aws.js.map +1 -1
  25. package/lib/cmap/auth/providers.js +1 -0
  26. package/lib/cmap/auth/providers.js.map +1 -1
  27. package/lib/cmap/connect.js +1 -1
  28. package/lib/cmap/connect.js.map +1 -1
  29. package/lib/cmap/connection.js +27 -28
  30. package/lib/cmap/connection.js.map +1 -1
  31. package/lib/cmap/connection_pool.js +59 -59
  32. package/lib/cmap/connection_pool.js.map +1 -1
  33. package/lib/cmap/errors.js +1 -1
  34. package/lib/cmap/errors.js.map +1 -1
  35. package/lib/cmap/handshake/client_metadata.js +5 -7
  36. package/lib/cmap/handshake/client_metadata.js.map +1 -1
  37. package/lib/cmap/metrics.js +3 -3
  38. package/lib/cmap/metrics.js.map +1 -1
  39. package/lib/cmap/wire_protocol/constants.js +1 -3
  40. package/lib/cmap/wire_protocol/constants.js.map +1 -1
  41. package/lib/cmap/wire_protocol/on_data.js +1 -0
  42. package/lib/cmap/wire_protocol/on_data.js.map +1 -1
  43. package/lib/cmap/wire_protocol/responses.js +2 -2
  44. package/lib/cmap/wire_protocol/responses.js.map +1 -1
  45. package/lib/collection.js +1 -1
  46. package/lib/collection.js.map +1 -1
  47. package/lib/connection_string.js +10 -8
  48. package/lib/connection_string.js.map +1 -1
  49. package/lib/cursor/abstract_cursor.js +34 -17
  50. package/lib/cursor/abstract_cursor.js.map +1 -1
  51. package/lib/cursor/change_stream_cursor.js +2 -2
  52. package/lib/cursor/change_stream_cursor.js.map +1 -1
  53. package/lib/cursor/find_cursor.js +26 -37
  54. package/lib/cursor/find_cursor.js.map +1 -1
  55. package/lib/cursor/run_command_cursor.js +1 -1
  56. package/lib/cursor/run_command_cursor.js.map +1 -1
  57. package/lib/db.js +6 -6
  58. package/lib/db.js.map +1 -1
  59. package/lib/error.js +2 -2
  60. package/lib/error.js.map +1 -1
  61. package/lib/gridfs/download.js +5 -5
  62. package/lib/gridfs/download.js.map +1 -1
  63. package/lib/gridfs/index.js +9 -9
  64. package/lib/gridfs/index.js.map +1 -1
  65. package/lib/gridfs/upload.js +8 -2
  66. package/lib/gridfs/upload.js.map +1 -1
  67. package/lib/index.js +4 -2
  68. package/lib/index.js.map +1 -1
  69. package/lib/mongo_client.js +67 -58
  70. package/lib/mongo_client.js.map +1 -1
  71. package/lib/mongo_client_auth_providers.js +6 -0
  72. package/lib/mongo_client_auth_providers.js.map +1 -1
  73. package/lib/mongo_logger.js.map +1 -1
  74. package/lib/mongo_types.js +2 -1
  75. package/lib/mongo_types.js.map +1 -1
  76. package/lib/operations/aggregate.js +3 -0
  77. package/lib/operations/aggregate.js.map +1 -1
  78. package/lib/operations/command.js.map +1 -1
  79. package/lib/operations/create_collection.js +1 -0
  80. package/lib/operations/create_collection.js.map +1 -1
  81. package/lib/operations/drop.js +9 -8
  82. package/lib/operations/drop.js.map +1 -1
  83. package/lib/operations/execute_operation.js +1 -3
  84. package/lib/operations/execute_operation.js.map +1 -1
  85. package/lib/operations/find.js.map +1 -1
  86. package/lib/read_preference.js +14 -10
  87. package/lib/read_preference.js.map +1 -1
  88. package/lib/resource_management.js +58 -0
  89. package/lib/resource_management.js.map +1 -0
  90. package/lib/sdam/server.js +14 -14
  91. package/lib/sdam/server.js.map +1 -1
  92. package/lib/sdam/srv_polling.js +2 -2
  93. package/lib/sdam/srv_polling.js.map +1 -1
  94. package/lib/sdam/topology.js +68 -24
  95. package/lib/sdam/topology.js.map +1 -1
  96. package/lib/sessions.js +4 -5
  97. package/lib/sessions.js.map +1 -1
  98. package/lib/transactions.js +13 -2
  99. package/lib/transactions.js.map +1 -1
  100. package/lib/utils.js +14 -0
  101. package/lib/utils.js.map +1 -1
  102. package/mongodb.d.ts +244 -72
  103. package/package.json +20 -17
  104. package/src/beta.ts +22 -0
  105. package/src/bulk/common.ts +11 -9
  106. package/src/change_stream.ts +37 -85
  107. package/src/client-side-encryption/auto_encrypter.ts +12 -6
  108. package/src/client-side-encryption/client_encryption.ts +6 -5
  109. package/src/client-side-encryption/crypto_callbacks.ts +87 -0
  110. package/src/client-side-encryption/errors.ts +0 -3
  111. package/src/cmap/auth/aws_temporary_credentials.ts +70 -12
  112. package/src/cmap/auth/mongo_credentials.ts +21 -1
  113. package/src/cmap/auth/mongodb_aws.ts +17 -8
  114. package/src/cmap/auth/providers.ts +1 -0
  115. package/src/cmap/connect.ts +1 -1
  116. package/src/cmap/connection.ts +18 -14
  117. package/src/cmap/connection_pool.ts +13 -4
  118. package/src/cmap/errors.ts +1 -1
  119. package/src/cmap/handshake/client_metadata.ts +26 -18
  120. package/src/cmap/wire_protocol/constants.ts +0 -2
  121. package/src/cmap/wire_protocol/on_data.ts +2 -1
  122. package/src/collection.ts +1 -1
  123. package/src/connection_string.ts +20 -13
  124. package/src/cursor/abstract_cursor.ts +52 -12
  125. package/src/cursor/change_stream_cursor.ts +2 -2
  126. package/src/cursor/find_cursor.ts +27 -40
  127. package/src/cursor/run_command_cursor.ts +1 -1
  128. package/src/error.ts +2 -2
  129. package/src/gridfs/download.ts +4 -0
  130. package/src/gridfs/upload.ts +22 -0
  131. package/src/index.ts +8 -2
  132. package/src/mongo_client.ts +100 -68
  133. package/src/mongo_client_auth_providers.ts +8 -0
  134. package/src/mongo_logger.ts +1 -1
  135. package/src/mongo_types.ts +2 -1
  136. package/src/operations/aggregate.ts +6 -0
  137. package/src/operations/command.ts +12 -0
  138. package/src/operations/create_collection.ts +3 -0
  139. package/src/operations/drop.ts +11 -9
  140. package/src/operations/execute_operation.ts +2 -6
  141. package/src/operations/find.ts +11 -2
  142. package/src/read_preference.ts +9 -0
  143. package/src/resource_management.ts +74 -0
  144. package/src/sdam/topology.ts +60 -2
  145. package/src/sessions.ts +8 -2
  146. package/src/transactions.ts +17 -2
  147. package/src/utils.ts +18 -0
  148. package/tsconfig.json +7 -5
  149. package/lib/operations/end_sessions.js +0 -34
  150. package/lib/operations/end_sessions.js.map +0 -1
  151. package/src/operations/end_sessions.ts +0 -44
@@ -21,6 +21,14 @@ const AUTH_PROVIDERS = new Map<
21
21
  AuthMechanism.MONGODB_AWS,
22
22
  ({ AWS_CREDENTIAL_PROVIDER }) => new MongoDBAWS(AWS_CREDENTIAL_PROVIDER)
23
23
  ],
24
+ [
25
+ AuthMechanism.MONGODB_CR,
26
+ () => {
27
+ throw new MongoInvalidArgumentError(
28
+ 'MONGODB-CR is no longer a supported auth mechanism in MongoDB 4.0+'
29
+ );
30
+ }
31
+ ],
24
32
  [AuthMechanism.MONGODB_GSSAPI, () => new GSSAPI()],
25
33
  [AuthMechanism.MONGODB_OIDC, properties => new MongoDBOIDC(getWorkflow(properties))],
26
34
  [AuthMechanism.MONGODB_PLAIN, () => new Plain()],
@@ -240,7 +240,7 @@ export function createStdioLogger(stream: {
240
240
  write: NodeJS.WriteStream['write'];
241
241
  }): MongoDBLogWritable {
242
242
  return {
243
- write: promisify((log: Log, cb: (error?: Error | null) => void): unknown => {
243
+ write: promisify((log: Log, cb: (error?: Error) => void): unknown => {
244
244
  const logLine = inspect(log, { compact: true, breakLength: Infinity });
245
245
  stream.write(`${logLine}\n`, 'utf-8', cb);
246
246
  return;
@@ -473,7 +473,8 @@ export class TypedEventEmitter<Events extends EventsDescription> extends EventEm
473
473
  }
474
474
 
475
475
  /**
476
- * @internal
476
+ * @public
477
+ * @deprecated Will be removed in favor of `AbortSignal` in the next major release.
477
478
  */
478
479
  export class CancellationToken extends TypedEventEmitter<{ cancel(): void }> {
479
480
  constructor(...args: any[]) {
@@ -80,6 +80,12 @@ export class AggregateOperation extends CommandOperation<CursorResponse> {
80
80
  delete this.options.writeConcern;
81
81
  }
82
82
 
83
+ if (this.explain && this.writeConcern) {
84
+ throw new MongoInvalidArgumentError(
85
+ 'Option "explain" cannot be used on an aggregate call with writeConcern'
86
+ );
87
+ }
88
+
83
89
  if (options?.cursor != null && typeof options.cursor !== 'object') {
84
90
  throw new MongoInvalidArgumentError('Cursor options must be an object');
85
91
  }
@@ -53,9 +53,21 @@ export interface CommandOperationOptions
53
53
  * In server versions 4.4 and above, 'comment' can be any valid BSON type.
54
54
  */
55
55
  comment?: unknown;
56
+ /**
57
+ * @deprecated
58
+ * This option is deprecated and will be removed in a future release as it is not used
59
+ * in the driver. Use MongoClientOptions or connection string parameters instead.
60
+ * */
61
+ retryWrites?: boolean;
62
+
56
63
  // Admin command overrides.
57
64
  dbName?: string;
58
65
  authdb?: string;
66
+ /**
67
+ * @deprecated
68
+ * This option is deprecated and will be removed in an upcoming major version.
69
+ */
70
+ noResponse?: boolean;
59
71
 
60
72
  /**
61
73
  * Used when the command needs to grant access to the underlying namespaces for time series collections.
@@ -23,6 +23,7 @@ const ILLEGAL_COMMAND_FIELDS = new Set([
23
23
  'timeoutMS',
24
24
  'j',
25
25
  'fsync',
26
+ 'autoIndexId',
26
27
  'pkFactory',
27
28
  'raw',
28
29
  'readPreference',
@@ -67,6 +68,8 @@ export interface ClusteredCollectionOptions extends Document {
67
68
  export interface CreateCollectionOptions extends Omit<CommandOperationOptions, 'rawData'> {
68
69
  /** Create a capped collection */
69
70
  capped?: boolean;
71
+ /** @deprecated Create an index on the _id field of the document. This option is deprecated in MongoDB 3.2+ and will be removed once no longer supported by the server. */
72
+ autoIndexId?: boolean;
70
73
  /** The size of the capped collection in bytes */
71
74
  size?: number;
72
75
  /** The maximum number of documents in the capped collection */
@@ -1,4 +1,4 @@
1
- import { type Connection, type MongoError, MongoServerError } from '..';
1
+ import { type Connection, MongoServerError } from '..';
2
2
  import type { Document } from '../bson';
3
3
  import { MongoDBResponse } from '../cmap/wire_protocol/responses';
4
4
  import { CursorTimeoutContext } from '../cursor/abstract_cursor';
@@ -40,13 +40,6 @@ export class DropCollectionOperation extends CommandOperation<boolean> {
40
40
  override handleOk(_response: InstanceType<typeof this.SERVER_COMMAND_RESPONSE_TYPE>): boolean {
41
41
  return true;
42
42
  }
43
-
44
- override handleError(error: MongoError): boolean {
45
- if (!(error instanceof MongoServerError)) throw error;
46
- if (Number(error.code) !== MONGODB_ERROR_CODES.NamespaceNotFound) throw error;
47
-
48
- return false;
49
- }
50
43
  }
51
44
 
52
45
  export async function dropCollections(
@@ -90,7 +83,16 @@ export async function dropCollections(
90
83
  for (const collectionName of [escCollection, ecocCollection]) {
91
84
  // Drop auxilliary collections, ignoring potential NamespaceNotFound errors.
92
85
  const dropOp = new DropCollectionOperation(db, collectionName, options);
93
- await executeOperation(db.client, dropOp, timeoutContext);
86
+ try {
87
+ await executeOperation(db.client, dropOp, timeoutContext);
88
+ } catch (err) {
89
+ if (
90
+ !(err instanceof MongoServerError) ||
91
+ err.code !== MONGODB_ERROR_CODES.NamespaceNotFound
92
+ ) {
93
+ throw err;
94
+ }
95
+ }
94
96
  }
95
97
  }
96
98
 
@@ -1,4 +1,3 @@
1
- import { MIN_SUPPORTED_SNAPSHOT_READS_WIRE_VERSION } from '../cmap/wire_protocol/constants';
2
1
  import {
3
2
  isRetryableReadError,
4
3
  isRetryableWriteError,
@@ -26,7 +25,7 @@ import {
26
25
  import type { Topology } from '../sdam/topology';
27
26
  import type { ClientSession } from '../sessions';
28
27
  import { TimeoutContext } from '../timeout';
29
- import { abortable, maxWireVersion, supportsRetryableWrites } from '../utils';
28
+ import { abortable, supportsRetryableWrites } from '../utils';
30
29
  import { AggregateOperation } from './aggregate';
31
30
  import { AbstractOperation, Aspect } from './operation';
32
31
 
@@ -82,10 +81,7 @@ export async function executeOperation<
82
81
  session = client.startSession({ owner, explicit: false });
83
82
  } else if (session.hasEnded) {
84
83
  throw new MongoExpiredSessionError('Use of expired sessions is not permitted');
85
- } else if (
86
- session.snapshotEnabled &&
87
- maxWireVersion(topology) < MIN_SUPPORTED_SNAPSHOT_READS_WIRE_VERSION
88
- ) {
84
+ } else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) {
89
85
  throw new MongoCompatibilityError('Snapshot reads require MongoDB 5.0 or later');
90
86
  } else if (session.client !== client) {
91
87
  throw new MongoInvalidArgumentError('ClientSession must be from the same MongoClient');
@@ -12,8 +12,10 @@ import { Aspect, defineAspects, type Hint } from './operation';
12
12
 
13
13
  /**
14
14
  * @public
15
+ * @typeParam TSchema - Unused schema definition, deprecated usage, only specify `FindOptions` with no generic
15
16
  */
16
- export interface FindOptions
17
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
18
+ export interface FindOptions<TSchema extends Document = Document>
17
19
  extends Omit<CommandOperationOptions, 'writeConcern' | 'explain'>,
18
20
  AbstractCursorOptions {
19
21
  /** Sets the limit of documents returned in the query. */
@@ -74,7 +76,14 @@ export interface FindOptions
74
76
  }
75
77
 
76
78
  /** @public */
77
- export type FindOneOptions = Omit<FindOptions, 'batchSize' | 'limit' | 'noCursorTimeout'>;
79
+ export interface FindOneOptions extends FindOptions {
80
+ /** @deprecated Will be removed in the next major version. User provided value will be ignored. */
81
+ batchSize?: number;
82
+ /** @deprecated Will be removed in the next major version. User provided value will be ignored. */
83
+ limit?: number;
84
+ /** @deprecated Will be removed in the next major version. User provided value will be ignored. */
85
+ noCursorTimeout?: boolean;
86
+ }
78
87
 
79
88
  /** @internal */
80
89
  export class FindOperation extends CommandOperation<CursorResponse> {
@@ -63,6 +63,10 @@ export class ReadPreference {
63
63
  tags?: TagSet[];
64
64
  hedge?: HedgeOptions;
65
65
  maxStalenessSeconds?: number;
66
+ /**
67
+ * @deprecated This will be removed as dead code in the next major version.
68
+ */
69
+ minWireVersion?: number;
66
70
 
67
71
  public static PRIMARY = ReadPreferenceMode.primary;
68
72
  public static PRIMARY_PREFERRED = ReadPreferenceMode.primaryPreferred;
@@ -96,6 +100,7 @@ export class ReadPreference {
96
100
  this.tags = tags;
97
101
  this.hedge = options?.hedge;
98
102
  this.maxStalenessSeconds = undefined;
103
+ this.minWireVersion = undefined;
99
104
 
100
105
  options = options ?? {};
101
106
  if (options.maxStalenessSeconds != null) {
@@ -104,6 +109,10 @@ export class ReadPreference {
104
109
  }
105
110
 
106
111
  this.maxStalenessSeconds = options.maxStalenessSeconds;
112
+
113
+ // NOTE: The minimum required wire version is 5 for this read preference. If the existing
114
+ // topology has a lower value then a MongoError will be thrown during server selection.
115
+ this.minWireVersion = 5;
107
116
  }
108
117
 
109
118
  if (this.mode === ReadPreference.PRIMARY) {
@@ -0,0 +1,74 @@
1
+ /**
2
+ * @public
3
+ */
4
+ export interface AsyncDisposable {
5
+ /**
6
+ * @beta
7
+ * @experimental
8
+ */
9
+ [Symbol.asyncDispose](): Promise<void>;
10
+
11
+ /**
12
+ * @internal
13
+ *
14
+ * A method that wraps disposal semantics for a given resource in the class.
15
+ */
16
+ asyncDispose(): Promise<void>;
17
+ }
18
+
19
+ /** @internal */
20
+ export function configureResourceManagement(target: AsyncDisposable) {
21
+ Symbol.asyncDispose &&
22
+ Object.defineProperty(target, Symbol.asyncDispose, {
23
+ value: async function asyncDispose(this: AsyncDisposable) {
24
+ await this.asyncDispose();
25
+ },
26
+ enumerable: false,
27
+ configurable: true,
28
+ writable: true
29
+ });
30
+ }
31
+
32
+ /**
33
+ * @beta
34
+ * @experimental
35
+ *
36
+ * Attaches `Symbol.asyncDispose` methods to the MongoClient, Cursors, sessions and change streams
37
+ * if Symbol.asyncDispose is defined.
38
+ *
39
+ * It's usually not necessary to call this method - the driver attempts to attach these methods
40
+ * itself when its loaded. However, sometimes the driver may be loaded before `Symbol.asyncDispose`
41
+ * is defined, in which case it is necessary to call this method directly. This can happen if the
42
+ * application is polyfilling `Symbol.asyncDispose`.
43
+ *
44
+ * Example:
45
+ *
46
+ * ```typescript
47
+ * import { configureExplicitResourceManagement, MongoClient } from 'mongodb/lib/beta';
48
+ *
49
+ * Symbol.asyncDispose ??= Symbol('dispose');
50
+ * load();
51
+ *
52
+ * await using client = new MongoClient(...);
53
+ * ```
54
+ */
55
+ export function configureExplicitResourceManagement() {
56
+ // We must import lazily here, because there's a circular dependency between the resource management
57
+ // file and each resources' file. We could move `configureResourceManagement` to a separate
58
+ // function, but keeping all resource-management related code together seemed preferable and I chose
59
+ // lazy requiring of resources instead.
60
+
61
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
62
+ const { MongoClient } = require('./mongo_client');
63
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
64
+ const { ClientSession } = require('./sessions');
65
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
66
+ const { AbstractCursor } = require('./cursor/abstract_cursor');
67
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
68
+ const { ChangeStream } = require('./change_stream');
69
+
70
+ configureResourceManagement(MongoClient.prototype);
71
+ configureResourceManagement(ClientSession.prototype);
72
+ configureResourceManagement(AbstractCursor.prototype);
73
+ configureResourceManagement(ChangeStream.prototype);
74
+ }
@@ -150,7 +150,8 @@ export interface TopologyOptions extends BSONSerializeOptions, ServerOptions {
150
150
  /** Indicates that a client should directly connect to a node without attempting to discover its topology type */
151
151
  directConnection: boolean;
152
152
  loadBalanced: boolean;
153
- metadata: Promise<ClientMetadata>;
153
+ metadata: ClientMetadata;
154
+ extendedMetadata: Promise<Document>;
154
155
  serverMonitoringMode: ServerMonitoringMode;
155
156
  /** MongoDB server API version */
156
157
  serverApi?: ServerApi;
@@ -392,6 +393,10 @@ export class Topology extends TypedEventEmitter<TopologyEvents> {
392
393
  return this.s.options.serverApi;
393
394
  }
394
395
 
396
+ get capabilities(): ServerCapabilities {
397
+ return new ServerCapabilities(this.lastHello());
398
+ }
399
+
395
400
  /** Initiate server connect */
396
401
  async connect(options?: ConnectOptions): Promise<Topology> {
397
402
  this.connectionLock ??= this._connect(options);
@@ -465,7 +470,7 @@ export class Topology extends TypedEventEmitter<TopologyEvents> {
465
470
  );
466
471
 
467
472
  const skipPingOnConnect = this.s.options.__skipPingOnConnect === true;
468
- if (!skipPingOnConnect) {
473
+ if (!skipPingOnConnect && this.s.credentials) {
469
474
  const connection = await server.pool.checkOut({ timeoutContext: timeoutContext });
470
475
  server.pool.checkIn(connection);
471
476
  stateTransition(this, STATE_CONNECTED);
@@ -749,6 +754,10 @@ export class Topology extends TypedEventEmitter<TopologyEvents> {
749
754
  if (typeof callback === 'function') callback(undefined, true);
750
755
  }
751
756
 
757
+ get clientMetadata(): ClientMetadata {
758
+ return this.s.options.metadata;
759
+ }
760
+
752
761
  isConnected(): boolean {
753
762
  return this.s.state === STATE_CONNECTED;
754
763
  }
@@ -1094,3 +1103,52 @@ function isStaleServerDescription(
1094
1103
  compareTopologyVersion(currentTopologyVersion, incomingServerDescription.topologyVersion) > 0
1095
1104
  );
1096
1105
  }
1106
+
1107
+ /**
1108
+ * @public
1109
+ * @deprecated This class will be removed as dead code in the next major version.
1110
+ */
1111
+ export class ServerCapabilities {
1112
+ maxWireVersion: number;
1113
+ minWireVersion: number;
1114
+
1115
+ constructor(hello: Document) {
1116
+ this.minWireVersion = hello.minWireVersion || 0;
1117
+ this.maxWireVersion = hello.maxWireVersion || 0;
1118
+ }
1119
+
1120
+ get hasAggregationCursor(): boolean {
1121
+ return true;
1122
+ }
1123
+
1124
+ get hasWriteCommands(): boolean {
1125
+ return true;
1126
+ }
1127
+ get hasTextSearch(): boolean {
1128
+ return true;
1129
+ }
1130
+
1131
+ get hasAuthCommands(): boolean {
1132
+ return true;
1133
+ }
1134
+
1135
+ get hasListCollectionsCommand(): boolean {
1136
+ return true;
1137
+ }
1138
+
1139
+ get hasListIndexesCommand(): boolean {
1140
+ return true;
1141
+ }
1142
+
1143
+ get supportsSnapshotReads(): boolean {
1144
+ return this.maxWireVersion >= 13;
1145
+ }
1146
+
1147
+ get commandsTakeWriteConcern(): boolean {
1148
+ return true;
1149
+ }
1150
+
1151
+ get commandsTakeCollation(): boolean {
1152
+ return true;
1153
+ }
1154
+ }
package/src/sessions.ts CHANGED
@@ -26,6 +26,7 @@ import { executeOperation } from './operations/execute_operation';
26
26
  import { RunCommandOperation } from './operations/run_command';
27
27
  import { ReadConcernLevel } from './read_concern';
28
28
  import { ReadPreference } from './read_preference';
29
+ import { type AsyncDisposable, configureResourceManagement } from './resource_management';
29
30
  import { _advanceClusterTime, type ClusterTime, TopologyType } from './sdam/common';
30
31
  import { TimeoutContext } from './timeout';
31
32
  import {
@@ -117,7 +118,7 @@ export class ClientSession
117
118
  /** @internal */
118
119
  owner?: symbol | AbstractCursor;
119
120
  defaultTransactionOptions: TransactionOptions;
120
- /** @internal */
121
+ /** @deprecated - Will be made internal in the next major release */
121
122
  transaction: Transaction;
122
123
  /**
123
124
  * @internal
@@ -288,10 +289,13 @@ export class ClientSession
288
289
  }
289
290
  }
290
291
  /**
292
+ * @beta
291
293
  * @experimental
292
294
  * An alias for {@link ClientSession.endSession|ClientSession.endSession()}.
293
295
  */
294
- async [Symbol.asyncDispose]() {
296
+ declare [Symbol.asyncDispose]: () => Promise<void>;
297
+ /** @internal */
298
+ async asyncDispose() {
295
299
  await this.endSession({ force: true });
296
300
  }
297
301
 
@@ -819,6 +823,8 @@ export class ClientSession
819
823
  }
820
824
  }
821
825
 
826
+ configureResourceManagement(ClientSession.prototype);
827
+
822
828
  const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([
823
829
  'CannotSatisfyWriteConcern',
824
830
  'UnknownReplWriteConcern',
@@ -73,15 +73,21 @@ export interface TransactionOptions extends Omit<CommandOperationOptions, 'timeo
73
73
  }
74
74
 
75
75
  /**
76
- * @internal
76
+ * @public
77
+ * @deprecated - Will be made internal in a future major release.
78
+ * A class maintaining state related to a server transaction. Internal Only
77
79
  */
78
80
  export class Transaction {
81
+ /** @internal */
79
82
  state: TxnState;
83
+ /** @deprecated - Will be made internal in a future major release. */
80
84
  options: TransactionOptions;
85
+ /** @internal */
81
86
  _pinnedServer?: Server;
87
+ /** @internal */
82
88
  _recoveryToken?: Document;
83
89
 
84
- /** Create a transaction */
90
+ /** Create a transaction @internal */
85
91
  constructor(options?: TransactionOptions) {
86
92
  options = options ?? {};
87
93
  this.state = TxnState.NO_TRANSACTION;
@@ -113,19 +119,23 @@ export class Transaction {
113
119
  this._recoveryToken = undefined;
114
120
  }
115
121
 
122
+ /** @internal */
116
123
  get server(): Server | undefined {
117
124
  return this._pinnedServer;
118
125
  }
119
126
 
127
+ /** @deprecated - Will be made internal in a future major release. */
120
128
  get recoveryToken(): Document | undefined {
121
129
  return this._recoveryToken;
122
130
  }
123
131
 
132
+ /** @deprecated - Will be made internal in a future major release. */
124
133
  get isPinned(): boolean {
125
134
  return !!this.server;
126
135
  }
127
136
 
128
137
  /**
138
+ * @deprecated - Will be made internal in a future major release.
129
139
  * @returns Whether the transaction has started
130
140
  */
131
141
  get isStarting(): boolean {
@@ -133,17 +143,20 @@ export class Transaction {
133
143
  }
134
144
 
135
145
  /**
146
+ * @deprecated - Will be made internal in a future major release.
136
147
  * @returns Whether this session is presently in a transaction
137
148
  */
138
149
  get isActive(): boolean {
139
150
  return ACTIVE_STATES.has(this.state);
140
151
  }
141
152
 
153
+ /** @deprecated - Will be made internal in a future major release. */
142
154
  get isCommitted(): boolean {
143
155
  return COMMITTED_STATES.has(this.state);
144
156
  }
145
157
  /**
146
158
  * Transition the transaction in the state machine
159
+ * @internal
147
160
  * @param nextState - The new state to transition to
148
161
  */
149
162
  transition(nextState: TxnState): void {
@@ -165,12 +178,14 @@ export class Transaction {
165
178
  );
166
179
  }
167
180
 
181
+ /** @internal */
168
182
  pinServer(server: Server): void {
169
183
  if (this.isActive) {
170
184
  this._pinnedServer = server;
171
185
  }
172
186
  }
173
187
 
188
+ /** @internal */
174
189
  unpinServer(): void {
175
190
  this._pinnedServer = undefined;
176
191
  }
package/src/utils.ts CHANGED
@@ -153,6 +153,24 @@ export function filterOptions(options: AnyOptions, names: ReadonlyArray<string>)
153
153
  return filterOptions;
154
154
  }
155
155
 
156
+ interface HasRetryableWrites {
157
+ retryWrites?: boolean;
158
+ }
159
+ /**
160
+ * Applies retryWrites: true to a command if retryWrites is set on the command's database.
161
+ * @internal
162
+ *
163
+ * @param target - The target command to which we will apply retryWrites.
164
+ * @param db - The database from which we can inherit a retryWrites value.
165
+ */
166
+ export function applyRetryableWrites<T extends HasRetryableWrites>(target: T, db?: Db): T {
167
+ if (db && db.s.options?.retryWrites) {
168
+ target.retryWrites = true;
169
+ }
170
+
171
+ return target;
172
+ }
173
+
156
174
  /**
157
175
  * Applies a write concern to a command based on well defined inheritance rules, optionally
158
176
  * detecting support for the write concern in the first place.
package/tsconfig.json CHANGED
@@ -4,12 +4,15 @@
4
4
  "checkJs": false,
5
5
  "strict": true,
6
6
  "alwaysStrict": true,
7
- "target": "ES2023",
7
+ "target": "ES2021",
8
8
  "module": "commonJS",
9
9
  "moduleResolution": "node",
10
10
  "skipLibCheck": true,
11
11
  "lib": [
12
- "es2023"
12
+ "es2021",
13
+ "ES2022.Error",
14
+ "ES2022.Object",
15
+ "esnext.disposable"
13
16
  ],
14
17
  // We don't make use of tslib helpers, all syntax used is supported by target engine
15
18
  "importHelpers": false,
@@ -33,8 +36,7 @@
33
36
  "noImplicitOverride": true,
34
37
  "noImplicitReturns": true,
35
38
  // TODO(NODE-3659): Enable useUnknownInCatchVariables and add type assertions or remove unnecessary catch blocks
36
- "useUnknownInCatchVariables": false,
37
- "useDefineForClassFields": false
39
+ "useUnknownInCatchVariables": false
38
40
  },
39
41
  "ts-node": {
40
42
  "transpileOnly": true,
@@ -43,4 +45,4 @@
43
45
  "include": [
44
46
  "src/**/*"
45
47
  ]
46
- }
48
+ }
@@ -1,34 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.EndSessionsOperation = void 0;
4
- const responses_1 = require("../cmap/wire_protocol/responses");
5
- const command_1 = require("../operations/command");
6
- const read_preference_1 = require("../read_preference");
7
- const utils_1 = require("../utils");
8
- const operation_1 = require("./operation");
9
- class EndSessionsOperation extends command_1.CommandOperation {
10
- constructor(sessions) {
11
- super();
12
- this.writeConcern = { w: 0 };
13
- this.ns = utils_1.MongoDBNamespace.fromString('admin.$cmd');
14
- this.SERVER_COMMAND_RESPONSE_TYPE = responses_1.MongoDBResponse;
15
- this.sessions = sessions;
16
- }
17
- buildCommandDocument(_connection, _session) {
18
- return {
19
- endSessions: this.sessions
20
- };
21
- }
22
- buildOptions(timeoutContext) {
23
- return {
24
- timeoutContext,
25
- readPreference: read_preference_1.ReadPreference.primaryPreferred
26
- };
27
- }
28
- get commandName() {
29
- return 'endSessions';
30
- }
31
- }
32
- exports.EndSessionsOperation = EndSessionsOperation;
33
- (0, operation_1.defineAspects)(EndSessionsOperation, operation_1.Aspect.WRITE_OPERATION);
34
- //# sourceMappingURL=end_sessions.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"end_sessions.js","sourceRoot":"","sources":["../../src/operations/end_sessions.ts"],"names":[],"mappings":";;;AASA,+DAAkE;AAClE,mDAAyD;AACzD,wDAAoD;AACpD,oCAA4C;AAC5C,2CAAoD;AAEpD,MAAa,oBAAqB,SAAQ,0BAAsB;IAO9D,YAAY,QAAgC;QAC1C,KAAK,EAAE,CAAC;QAPD,iBAAY,GAAiB,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;QACtC,OAAE,GAAG,wBAAgB,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;QAC/C,iCAA4B,GAAG,2BAAe,CAAC;QAMtD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAEQ,oBAAoB,CAAC,WAAuB,EAAE,QAAwB;QAC7E,OAAO;YACL,WAAW,EAAE,IAAI,CAAC,QAAQ;SAC3B,CAAC;IACJ,CAAC;IACQ,YAAY,CAAC,cAA8B;QAClD,OAAO;YACL,cAAc;YACd,cAAc,EAAE,gCAAc,CAAC,gBAAgB;SAChD,CAAC;IACJ,CAAC;IACD,IAAa,WAAW;QACtB,OAAO,aAAa,CAAC;IACvB,CAAC;CACF;AA1BD,oDA0BC;AAED,IAAA,yBAAa,EAAC,oBAAoB,EAAE,kBAAM,CAAC,eAAe,CAAC,CAAC"}
@@ -1,44 +0,0 @@
1
- import {
2
- type ClientSession,
3
- type Connection,
4
- type ServerCommandOptions,
5
- type ServerSessionId,
6
- type TimeoutContext,
7
- type WriteConcern
8
- } from '..';
9
- import { type Document } from '../bson';
10
- import { MongoDBResponse } from '../cmap/wire_protocol/responses';
11
- import { CommandOperation } from '../operations/command';
12
- import { ReadPreference } from '../read_preference';
13
- import { MongoDBNamespace } from '../utils';
14
- import { Aspect, defineAspects } from './operation';
15
-
16
- export class EndSessionsOperation extends CommandOperation<void> {
17
- override writeConcern: WriteConcern = { w: 0 };
18
- override ns = MongoDBNamespace.fromString('admin.$cmd');
19
- override SERVER_COMMAND_RESPONSE_TYPE = MongoDBResponse;
20
-
21
- private sessions: Array<ServerSessionId>;
22
-
23
- constructor(sessions: Array<ServerSessionId>) {
24
- super();
25
- this.sessions = sessions;
26
- }
27
-
28
- override buildCommandDocument(_connection: Connection, _session?: ClientSession): Document {
29
- return {
30
- endSessions: this.sessions
31
- };
32
- }
33
- override buildOptions(timeoutContext: TimeoutContext): ServerCommandOptions {
34
- return {
35
- timeoutContext,
36
- readPreference: ReadPreference.primaryPreferred
37
- };
38
- }
39
- override get commandName(): string {
40
- return 'endSessions';
41
- }
42
- }
43
-
44
- defineAspects(EndSessionsOperation, Aspect.WRITE_OPERATION);