"use strict";
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
    if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
    return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const errors_1 = require("@mongosh/errors");
const decorators_1 = require("./decorators");
const arg_parser_1 = require("@mongosh/arg-parser");
const database_1 = require("./database");
const result_1 = require("./result");
const result_2 = require("./result");
const mongodb_redact_1 = require("mongodb-redact");
const enums_1 = require("./enums");
const session_1 = __importDefault(require("./session"));
const helpers_1 = require("./helpers");
const change_stream_cursor_1 = __importDefault(require("./change-stream-cursor"));
const error_codes_1 = require("./error-codes");
const field_level_encryption_1 = require("./field-level-encryption");
const error_codes_2 = require("./error-codes");
const log_entry_1 = require("./log-entry");
let nextId = 1;
let Mongo = (() => {
    let _classDecorators = [decorators_1.shellApiClassDefault, (0, decorators_1.classPlatforms)(['CLI'])];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _classSuper = decorators_1.ShellApiClass;
    let _instanceExtraInitializers = [];
    let _getDB_decorators;
    let _getCollection_decorators;
    let _getDBs_decorators;
    let _bulkWrite_decorators;
    let _getDBNames_decorators;
    let _show_decorators;
    let _setReadPref_decorators;
    let _setReadConcern_decorators;
    let _setWriteConcern_decorators;
    let _startSession_decorators;
    let _setSlaveOk_decorators;
    let _setSecondaryOk_decorators;
    let _watch_decorators;
    let _getClientEncryption_decorators;
    let _getKeyVault_decorators;
    let _convertShardKeyToHashed_decorators;
    var Mongo = _classThis = class extends _classSuper {
        constructor(instanceState, uri, fleOptions, otherOptions, sp) {
            super();
            this.__serviceProvider = (__runInitializers(this, _instanceExtraInitializers), null);
            this._databases = Object.create(null);
            this._explicitEncryptionOnly = false;
            this._readPreferenceWasExplicitlyRequested = false;
            this._cachedDatabaseNames = [];
            this._connectionId = nextId++;
            this._instanceState = instanceState;
            if (sp) {
                this.__serviceProvider = sp;
            }
            if (typeof uri === 'object' &&
                uri !== null &&
                typeof uri._uri === 'string') {
                uri = uri._uri;
            }
            else if (typeof uri !== 'string') {
                uri = sp?.getURI?.() ?? 'mongodb://localhost/';
            }
            this._connectionInfo = (0, arg_parser_1.generateConnectionInfoFromCliArgs)({
                connectionSpecifier: uri,
            });
            this._readPreferenceWasExplicitlyRequested = /\breadPreference=/i.test(this._uri);
            if (fleOptions) {
                if (fleOptions.explicitEncryptionOnly !== undefined) {
                    if (fleOptions.schemaMap !== undefined) {
                        throw new errors_1.MongoshInvalidInputError('explicitEncryptionOnly and schemaMap are mutually exclusive', errors_1.CommonErrors.InvalidArgument);
                    }
                    fleOptions = { ...fleOptions };
                    this._explicitEncryptionOnly = !!fleOptions.explicitEncryptionOnly;
                    delete fleOptions.explicitEncryptionOnly;
                }
                this._connectionInfo.driverOptions.autoEncryption =
                    (0, helpers_1.processFLEOptions)(fleOptions);
            }
            else {
                const spFleOptions = sp?.getFleOptions?.();
                if (spFleOptions) {
                    this._connectionInfo.driverOptions.autoEncryption = spFleOptions;
                }
            }
            if (otherOptions?.api) {
                if (typeof otherOptions.api === 'string') {
                    this._connectionInfo.driverOptions.serverApi = {
                        version: otherOptions.api,
                    };
                }
                else {
                    this._connectionInfo.driverOptions.serverApi = otherOptions.api;
                }
            }
        }
        get _uri() {
            return this._connectionInfo.connectionString;
        }
        get _fleOptions() {
            return this._connectionInfo.driverOptions.autoEncryption;
        }
        get _serviceProvider() {
            if (this.__serviceProvider === null) {
                throw new errors_1.MongoshInternalError('No ServiceProvider available for this mongo', error_codes_2.ShellApiErrors.NotConnected);
            }
            return this.__serviceProvider;
        }
        set _serviceProvider(sp) {
            this.__serviceProvider = sp;
        }
        async _displayBatchSize() {
            return (this._instanceState.displayBatchSizeFromDBQuery ??
                (await this._instanceState.shellApi.config.get('displayBatchSize')));
        }
        [enums_1.asPrintable]() {
            return (0, mongodb_redact_1.redactConnectionString)(this._uri);
        }
        _emitMongoApiCall(methodName, methodArguments = {}) {
            this._instanceState.emitApiCallWithArgs({
                method: methodName,
                class: 'Mongo',
                uri: this._uri,
                arguments: methodArguments,
            });
        }
        async connect(username, password) {
            if (username || password) {
                this._connectionInfo = (0, arg_parser_1.mapCliToDriver)({
                    username,
                    password,
                }, this._connectionInfo);
            }
            const driverOptions = { ...this._connectionInfo.driverOptions };
            if (this._explicitEncryptionOnly) {
                delete driverOptions.autoEncryption;
            }
            else if (driverOptions.autoEncryption) {
                driverOptions.autoEncryption.extraOptions = {
                    ...driverOptions.autoEncryption.extraOptions,
                    ...(await this._instanceState.evaluationListener?.getCryptLibraryOptions?.()),
                };
            }
            const parentProvider = this._instanceState.initialServiceProvider;
            try {
                this.__serviceProvider = await parentProvider.getNewConnection(this._uri, driverOptions);
            }
            catch (e) {
                if (e?.name === 'MongoServerSelectionError' &&
                    parentProvider.getRawClient()?.options?.tls &&
                    !/\b(ssl|tls)=/.exec(this._uri)) {
                    e.message += ' (is ?tls=true missing from the connection string?)';
                }
                throw e;
            }
        }
        _getDb(name) {
            (0, helpers_1.assertArgsDefinedType)([name], ['string']);
            if (!(0, helpers_1.isValidDatabaseName)(name)) {
                throw new errors_1.MongoshInvalidInputError(`Invalid database name: ${name}`, errors_1.CommonErrors.InvalidArgument);
            }
            if (!(name in this._databases)) {
                this._databases[name] = new database_1.Database(this, name);
            }
            return this._databases[name];
        }
        getDB(db) {
            (0, helpers_1.assertArgsDefinedType)([db], ['string'], 'Mongo.getDB');
            this._instanceState.messageBus.emit('mongosh:getDB', { db });
            return this._getDb(db);
        }
        getCollection(name) {
            (0, helpers_1.assertArgsDefinedType)([name], ['string']);
            const { db, coll } = /^(?<db>[^.]+)\.(?<coll>.+)$/.exec(name)?.groups ?? {};
            if (!db || !coll) {
                throw new errors_1.MongoshInvalidInputError('Collection must be of the format <db>.<collection>', errors_1.CommonErrors.InvalidArgument);
            }
            return this._getDb(db).getCollection(coll);
        }
        _getConnectionId() {
            return `connection_${this._connectionId}`;
        }
        getURI() {
            return this._uri;
        }
        use(db) {
            (0, helpers_1.assertArgsDefinedType)([db], ['string'], 'Mongo.use');
            this._instanceState.messageBus.emit('mongosh:use', { db });
            let previousDbName;
            let previousDbMongo;
            try {
                const previousDb = this._instanceState.context.db;
                previousDbName = previousDb?.getName?.();
                previousDbMongo = previousDb?._mongo;
            }
            catch (e) {
                if (e?.code !== error_codes_2.ShellApiErrors.NotConnected) {
                    throw e;
                }
            }
            this._instanceState.context.db = this._getDb(db);
            if (db === previousDbName && previousDbMongo === this) {
                return `already on db ${db}`;
            }
            return `switched to db ${db}`;
        }
        async _listDatabases(opts = {}) {
            const result = await this._serviceProvider.listDatabases('admin', {
                ...this._getExplicitlyRequestedReadPref(),
                ...opts,
            });
            if (!('databases' in result)) {
                const err = new errors_1.MongoshRuntimeError('Got invalid result from "listDatabases"', errors_1.CommonErrors.CommandFailed);
                this._instanceState.messageBus.emit('mongosh:error', err, 'shell-api');
                throw err;
            }
            this._cachedDatabaseNames = result.databases.map((db) => db.name);
            return result;
        }
        async _getDatabaseNamesForCompletion() {
            return await Promise.race([
                (async () => {
                    const result = (await this._listDatabases({ readPreference: 'primaryPreferred' })).databases.map((db) => db.name);
                    this._instanceState.messageBus.emit('mongosh:load-databases-complete');
                    return result;
                })(),
                (async () => {
                    await new Promise((resolve) => setTimeout(resolve, 200)?.unref?.());
                    return this._cachedDatabaseNames;
                })(),
            ]);
        }
        async getDBs(options = {}) {
            this._emitMongoApiCall('getDBs', { options });
            return await this._listDatabases(options);
        }
        async bulkWrite(models, options = {}) {
            this._emitMongoApiCall('bulkWrite', { options });
            const { acknowledged, insertedCount, matchedCount, modifiedCount, deletedCount, upsertedCount, insertResults, updateResults, deleteResults, } = await this._serviceProvider.clientBulkWrite(models, options);
            return new result_1.ClientBulkWriteResult({
                acknowledged,
                insertedCount,
                matchedCount,
                modifiedCount,
                deletedCount,
                upsertedCount,
                insertResults,
                updateResults,
                deleteResults,
            });
        }
        async getDBNames(options = {}) {
            this._emitMongoApiCall('getDBNames', { options });
            return (await this._listDatabases(options)).databases.map((db) => db.name);
        }
        async show(cmd, arg, tracked = true) {
            const db = this._instanceState.currentDb;
            tracked &&
                this._instanceState.messageBus.emit('mongosh:show', {
                    method: `show ${cmd}`,
                });
            switch (cmd) {
                case 'databases':
                case 'dbs':
                    const result = (await this._listDatabases({
                        readPreference: 'primaryPreferred',
                        promoteLongs: true,
                    })).databases;
                    return new result_2.CommandResult('ShowDatabasesResult', result);
                case 'collections':
                case 'tables':
                    const collectionNames = await db._getCollectionNamesWithTypes({
                        readPreference: 'primaryPreferred',
                        promoteLongs: true,
                    });
                    return new result_2.CommandResult('ShowCollectionsResult', collectionNames);
                case 'profile':
                    const sysprof = db.getCollection('system.profile');
                    const profiles = {
                        count: await sysprof.countDocuments({}),
                    };
                    if (profiles.count !== 0) {
                        profiles.result = await (await sysprof.find({ millis: { $gt: 0 } }))
                            .sort({ $natural: -1 })
                            .limit(5)
                            .toArray();
                    }
                    return new result_2.CommandResult('ShowProfileResult', profiles);
                case 'users':
                    const users = await db.getUsers();
                    return new result_2.CommandResult('ShowResult', users.users);
                case 'roles':
                    const roles = await db.getRoles({ showBuiltinRoles: true });
                    return new result_2.CommandResult('ShowResult', roles.roles);
                case 'log':
                    const log = await db.adminCommand({ getLog: arg || 'global' });
                    return new result_2.CommandResult('ShowResult', log.log);
                case 'logs':
                    const logs = await db.adminCommand({ getLog: '*' });
                    return new result_2.CommandResult('ShowResult', logs.names);
                case 'startupWarnings': {
                    let result;
                    try {
                        result = (await db.adminCommand({
                            getLog: 'startupWarnings',
                        }));
                        if (!result) {
                            throw new errors_1.MongoshCommandFailed('adminCommand getLog unexpectedly returned no result');
                        }
                    }
                    catch (error) {
                        this._instanceState.messageBus.emit('mongosh:error', error, 'shell-api');
                        return new result_2.CommandResult('ShowBannerResult', null);
                    }
                    if (!result.log || !result.log.length) {
                        return new result_2.CommandResult('ShowBannerResult', null);
                    }
                    const lines = result.log.map((logLine) => {
                        try {
                            const entry = (0, log_entry_1.parseAnyLogEntry)(logLine);
                            return `${entry.timestamp}: ${entry.message}`;
                        }
                        catch (e) {
                            return `Unexpected log line format: ${logLine}`;
                        }
                    });
                    return new result_2.CommandResult('ShowBannerResult', {
                        header: 'The server generated these startup warnings when booting',
                        content: lines.join('\n'),
                    });
                }
                case 'automationNotices': {
                    let helloResult;
                    try {
                        helloResult = await db.hello();
                    }
                    catch (error) {
                        this._instanceState.messageBus.emit('mongosh:error', error, 'shell-api');
                        return new result_2.CommandResult('ShowBannerResult', null);
                    }
                    if (helloResult.automationServiceDescriptor) {
                        return new result_2.CommandResult('ShowBannerResult', {
                            content: `This server is managed by automation service '${helloResult.automationServiceDescriptor}'.\n` +
                                'Many administrative actions are inappropriate, and may be automatically reverted.',
                        });
                    }
                    return new result_2.CommandResult('ShowBannerResult', null);
                }
                case 'nonGenuineMongoDBCheck': {
                    const isGenuine = (await this._instanceState.fetchConnectionInfo())?.extraInfo
                        ?.is_genuine ?? true;
                    if (isGenuine) {
                        return new result_2.CommandResult('ShowBannerResult', null);
                    }
                    return new result_2.CommandResult('ShowBannerResult', {
                        header: 'Warning: Non-Genuine MongoDB Detected',
                        content: [
                            'This server or service appears to be an emulation of MongoDB rather than an official MongoDB product.',
                            'Some documented MongoDB features may work differently, be entirely missing or incomplete, or have unexpected performance characteristics.',
                            'To learn more please visit: https://dochub.mongodb.org/core/non-genuine-mongodb-server-warning.',
                        ].join('\n'),
                    });
                }
                default:
                    const err = new errors_1.MongoshInvalidInputError(`'${cmd}' is not a valid argument for "show".`, errors_1.CommonErrors.InvalidArgument);
                    this._instanceState.messageBus.emit('mongosh:error', err, 'shell-api');
                    throw err;
            }
        }
        async close() {
            const index = this._instanceState.mongos.indexOf(this);
            if (index === -1) {
                process.emitWarning(new errors_1.MongoshInternalError(`Closing untracked Mongo instance ${this[enums_1.asPrintable]()}`));
            }
            else {
                this._instanceState.mongos.splice(index, 1);
            }
            await this._serviceProvider.close();
        }
        async _suspend() {
            return await this._serviceProvider.suspend();
        }
        getReadPrefMode() {
            return this._serviceProvider.getReadPreference().mode;
        }
        getReadPrefTagSet() {
            return this._serviceProvider.getReadPreference().tags;
        }
        getReadPref() {
            return this._serviceProvider.getReadPreference();
        }
        _getExplicitlyRequestedReadPref() {
            return this._readPreferenceWasExplicitlyRequested
                ? { readPreference: this.getReadPref() }
                : undefined;
        }
        getReadConcern() {
            try {
                const rc = this._serviceProvider.getReadConcern();
                return rc ? rc.level : undefined;
            }
            catch {
                throw new errors_1.MongoshInternalError('Error retrieving ReadConcern.');
            }
        }
        getWriteConcern() {
            try {
                return this._serviceProvider.getWriteConcern();
            }
            catch {
                throw new errors_1.MongoshInternalError('Error retrieving WriteConcern.');
            }
        }
        async setReadPref(mode, tagSet, hedgeOptions) {
            await this._serviceProvider.resetConnectionOptions({
                readPreference: this._serviceProvider.readPreferenceFromOptions({
                    readPreference: mode,
                    readPreferenceTags: tagSet,
                    hedge: hedgeOptions,
                }),
            });
            this._readPreferenceWasExplicitlyRequested = true;
        }
        async setReadConcern(level) {
            await this._serviceProvider.resetConnectionOptions({
                readConcern: { level: level },
            });
        }
        async setWriteConcern(concernOrWValue, wtimeoutMSValue, jValue) {
            const options = {};
            let concern;
            if (typeof concernOrWValue === 'object') {
                if (wtimeoutMSValue !== undefined || jValue !== undefined) {
                    throw new errors_1.MongoshInvalidInputError('If concern is given as an object no other arguments must be specified', errors_1.CommonErrors.InvalidArgument);
                }
                concern = concernOrWValue;
            }
            else {
                concern = {};
                if (typeof concernOrWValue !== 'string' &&
                    typeof concernOrWValue !== 'number') {
                    throw new errors_1.MongoshInvalidInputError(`w value must be a number or string, got: ${typeof concernOrWValue}`, errors_1.CommonErrors.InvalidArgument);
                }
                else if (typeof concernOrWValue === 'number' && concernOrWValue < 0) {
                    throw new errors_1.MongoshInvalidInputError(`w value must be equal to or greather than 0, got: ${concernOrWValue}`, errors_1.CommonErrors.InvalidArgument);
                }
                concern.w = concernOrWValue;
                if (wtimeoutMSValue !== undefined) {
                    if (typeof wtimeoutMSValue !== 'number') {
                        throw new errors_1.MongoshInvalidInputError(`wtimeoutMS value must be a number, got: ${typeof wtimeoutMSValue}`, errors_1.CommonErrors.InvalidArgument);
                    }
                    else if (wtimeoutMSValue < 0) {
                        throw new errors_1.MongoshInvalidInputError(`wtimeoutMS must be equal to or greather than 0, got: ${wtimeoutMSValue}`, errors_1.CommonErrors.InvalidArgument);
                    }
                    concern.wtimeout = wtimeoutMSValue;
                }
                if (jValue !== undefined) {
                    if (typeof jValue !== 'boolean') {
                        throw new errors_1.MongoshInvalidInputError(`j value must be a boolean, got: ${typeof jValue}`, errors_1.CommonErrors.InvalidArgument);
                    }
                    concern.j = jValue;
                }
            }
            if (concern.w !== undefined) {
                options.w = concern.w;
            }
            if (concern.wtimeout !== undefined) {
                options.wtimeoutMS = concern.wtimeout;
            }
            if (concern.j !== undefined) {
                options.journal = concern.j;
            }
            if (concern.fsync !== undefined) {
                options.journal = !!concern.fsync;
            }
            await this._serviceProvider.resetConnectionOptions(options);
        }
        startSession(options = {}) {
            const allTransactionOptions = [
                'readConcern',
                'writeConcern',
                'readPreference',
                'maxCommitTimeMS',
            ];
            function assertAllTransactionOptionsUsed(_options) {
            }
            assertAllTransactionOptionsUsed('');
            const defaultTransactionOptions = {};
            for (const key of allTransactionOptions) {
                if (typeof options[key] !== 'undefined') {
                    defaultTransactionOptions[key] = options[key];
                }
            }
            const allSessionOptions = [
                'causalConsistency',
                'snapshot',
                'defaultTimeoutMS',
            ];
            function assertAllSessionOptionsUsed(_options) { }
            assertAllSessionOptionsUsed('');
            const driverOptions = {};
            if (Object.keys(defaultTransactionOptions).length > 0) {
                driverOptions.defaultTransactionOptions = defaultTransactionOptions;
            }
            for (const key of allSessionOptions) {
                if (typeof options[key] !== 'undefined') {
                    driverOptions[key] = options[key];
                }
            }
            return new session_1.default(this, driverOptions, this._serviceProvider.startSession(driverOptions));
        }
        setCausalConsistency() {
            throw new errors_1.MongoshUnimplementedError('It is not possible to set causal consistency for an entire connection due to the driver, use startSession({causalConsistency: <>}) instead.', errors_1.CommonErrors.NotImplemented, (0, error_codes_1.blockedByDriverMetadata)('Mongo.setCausalConsistency'));
        }
        isCausalConsistency() {
            throw new errors_1.MongoshUnimplementedError('Causal consistency for drivers is set via Mongo.startSession and can be checked via session.getOptions. The default value is true', errors_1.CommonErrors.NotImplemented, (0, error_codes_1.blockedByDriverMetadata)('Mongo.isCausalConsistency'));
        }
        setSlaveOk() {
            throw new errors_1.MongoshDeprecatedError('Setting slaveOk is deprecated, use setReadPref instead.');
        }
        async setSecondaryOk() {
            await this._instanceState.printDeprecationWarning('.setSecondaryOk() is deprecated. Use .setReadPref("primaryPreferred") instead');
            const currentReadPref = this.getReadPrefMode();
            if (currentReadPref === 'primary') {
                await this._instanceState.shellApi.print('Setting read preference from "primary" to "primaryPreferred"');
                await this.setReadPref('primaryPreferred');
            }
            else {
                await this._instanceState.shellApi.print(`Leaving read preference unchanged (is already "${currentReadPref}")`);
            }
        }
        async watch(pipeline = [], options = {}) {
            if (!Array.isArray(pipeline)) {
                options = pipeline;
                pipeline = [];
            }
            this._emitMongoApiCall('watch', { pipeline, options });
            const cursor = new change_stream_cursor_1.default(this._serviceProvider.watch(pipeline, options), (0, mongodb_redact_1.redactConnectionString)(this._uri), this);
            if (!options.resumeAfter &&
                !options.startAfter &&
                !options.startAtOperationTime) {
                await cursor.tryNext();
            }
            this._instanceState.currentCursor = cursor;
            return cursor;
        }
        getClientEncryption() {
            if (!this._fleOptions) {
                throw new errors_1.MongoshInvalidInputError('Cannot call getClientEncryption() without field-level encryption options', error_codes_2.ShellApiErrors.NotUsingFLE);
            }
            if (!this._clientEncryption) {
                this._clientEncryption = new field_level_encryption_1.ClientEncryption(this);
            }
            return this._clientEncryption;
        }
        async getKeyVault() {
            if (!this._keyVault) {
                this._keyVault = new field_level_encryption_1.KeyVault(this.getClientEncryption());
                await this._keyVault._init();
            }
            return this._keyVault;
        }
        async convertShardKeyToHashed(value) {
            const pipeline = [
                { $limit: 1 },
                { $project: { _id: { $toHashedIndexKey: { $literal: value } } } },
            ];
            let result;
            for (const approach of [
                () => this.getDB('_fakeDbForMongoshCSKTH').aggregate([
                    { $documents: [{}] },
                    ...pipeline,
                ]),
                () => this.getDB('admin').aggregate([
                    { $documents: [{}] },
                    ...pipeline,
                ]),
                () => this.getDB('admin')
                    .getCollection('system.version')
                    .aggregate(pipeline),
                () => this.getDB('local')
                    .getCollection('oplog.rs')
                    .aggregate([{ $collStats: {} }, ...pipeline]),
            ]) {
                try {
                    result = await (await approach()).next();
                }
                catch {
                    continue;
                }
                if (result)
                    break;
            }
            if (!result) {
                throw new errors_1.MongoshRuntimeError('Could not find a suitable way to run convertShardKeyToHashed() -- tried $documents and aggregating on admin.system.version and local.oplog.rs', errors_1.CommonErrors.CommandFailed);
            }
            return result._id;
        }
    };
    __setFunctionName(_classThis, "Mongo");
    (() => {
        const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
        _getDB_decorators = [(0, decorators_1.returnType)('Database')];
        _getCollection_decorators = [(0, decorators_1.returnType)('Collection')];
        _getDBs_decorators = [decorators_1.returnsPromise, (0, decorators_1.apiVersions)([1])];
        _bulkWrite_decorators = [decorators_1.returnsPromise, (0, decorators_1.serverVersions)(['8.0.0', enums_1.ServerVersions.latest]), (0, decorators_1.apiVersions)([1])];
        _getDBNames_decorators = [decorators_1.returnsPromise, (0, decorators_1.apiVersions)([1])];
        _show_decorators = [decorators_1.returnsPromise, (0, decorators_1.apiVersions)([1])];
        _setReadPref_decorators = [decorators_1.returnsPromise];
        _setReadConcern_decorators = [decorators_1.returnsPromise];
        _setWriteConcern_decorators = [decorators_1.returnsPromise];
        _startSession_decorators = [(0, decorators_1.topologies)(['ReplSet'])];
        _setSlaveOk_decorators = [decorators_1.deprecated];
        _setSecondaryOk_decorators = [decorators_1.deprecated, decorators_1.returnsPromise];
        _watch_decorators = [(0, decorators_1.serverVersions)(['3.1.0', enums_1.ServerVersions.latest]), (0, decorators_1.topologies)(['ReplSet', 'Sharded']), (0, decorators_1.apiVersions)([1]), decorators_1.returnsPromise];
        _getClientEncryption_decorators = [(0, decorators_1.platforms)(['CLI']), (0, decorators_1.serverVersions)(['4.2.0', enums_1.ServerVersions.latest]), (0, decorators_1.returnType)('ClientEncryption')];
        _getKeyVault_decorators = [(0, decorators_1.platforms)(['CLI']), (0, decorators_1.serverVersions)(['4.2.0', enums_1.ServerVersions.latest]), (0, decorators_1.returnType)('KeyVault'), decorators_1.returnsPromise];
        _convertShardKeyToHashed_decorators = [decorators_1.returnsPromise];
        __esDecorate(_classThis, null, _getDB_decorators, { kind: "method", name: "getDB", static: false, private: false, access: { has: obj => "getDB" in obj, get: obj => obj.getDB }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _getCollection_decorators, { kind: "method", name: "getCollection", static: false, private: false, access: { has: obj => "getCollection" in obj, get: obj => obj.getCollection }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _getDBs_decorators, { kind: "method", name: "getDBs", static: false, private: false, access: { has: obj => "getDBs" in obj, get: obj => obj.getDBs }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _bulkWrite_decorators, { kind: "method", name: "bulkWrite", static: false, private: false, access: { has: obj => "bulkWrite" in obj, get: obj => obj.bulkWrite }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _getDBNames_decorators, { kind: "method", name: "getDBNames", static: false, private: false, access: { has: obj => "getDBNames" in obj, get: obj => obj.getDBNames }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _show_decorators, { kind: "method", name: "show", static: false, private: false, access: { has: obj => "show" in obj, get: obj => obj.show }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _setReadPref_decorators, { kind: "method", name: "setReadPref", static: false, private: false, access: { has: obj => "setReadPref" in obj, get: obj => obj.setReadPref }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _setReadConcern_decorators, { kind: "method", name: "setReadConcern", static: false, private: false, access: { has: obj => "setReadConcern" in obj, get: obj => obj.setReadConcern }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _setWriteConcern_decorators, { kind: "method", name: "setWriteConcern", static: false, private: false, access: { has: obj => "setWriteConcern" in obj, get: obj => obj.setWriteConcern }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _startSession_decorators, { kind: "method", name: "startSession", static: false, private: false, access: { has: obj => "startSession" in obj, get: obj => obj.startSession }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _setSlaveOk_decorators, { kind: "method", name: "setSlaveOk", static: false, private: false, access: { has: obj => "setSlaveOk" in obj, get: obj => obj.setSlaveOk }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _setSecondaryOk_decorators, { kind: "method", name: "setSecondaryOk", static: false, private: false, access: { has: obj => "setSecondaryOk" in obj, get: obj => obj.setSecondaryOk }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _watch_decorators, { kind: "method", name: "watch", static: false, private: false, access: { has: obj => "watch" in obj, get: obj => obj.watch }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _getClientEncryption_decorators, { kind: "method", name: "getClientEncryption", static: false, private: false, access: { has: obj => "getClientEncryption" in obj, get: obj => obj.getClientEncryption }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _getKeyVault_decorators, { kind: "method", name: "getKeyVault", static: false, private: false, access: { has: obj => "getKeyVault" in obj, get: obj => obj.getKeyVault }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(_classThis, null, _convertShardKeyToHashed_decorators, { kind: "method", name: "convertShardKeyToHashed", static: false, private: false, access: { has: obj => "convertShardKeyToHashed" in obj, get: obj => obj.convertShardKeyToHashed }, metadata: _metadata }, null, _instanceExtraInitializers);
        __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
        Mongo = _classThis = _classDescriptor.value;
        if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        __runInitializers(_classThis, _classExtraInitializers);
    })();
    return Mongo = _classThis;
})();
exports.default = Mongo;
//# sourceMappingURL=mongo.js.map