"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = require("@pnpm/logger");
const server_1 = require("@pnpm/server");
const loadJsonFile = require("load-json-file");
const package_store_1 = require("package-store");
const path = require("path");
const retry = require("retry");
const createStore_1 = require("./createStore");
const runServerInBackground_1 = require("./runServerInBackground");
function default_1(opts) {
    return __awaiter(this, void 0, void 0, function* () {
        const store = yield package_store_1.resolveStore(opts.store, opts.prefix);
        try {
            const serverJson = yield loadJsonFile(path.join(store, 'server.json'));
            logger_1.default.info('A store server is running. All store manipulations are delegated to it.');
            return {
                ctrl: yield server_1.connectStoreController(serverJson.connectionOptions),
                path: store,
            };
        }
        catch (err) {
            if (err.code !== 'ENOENT')
                throw err;
        }
        if (opts.useStoreServer) {
            runServerInBackground_1.default(store);
            const operation = retry.operation();
            return new Promise((resolve, reject) => {
                operation.attempt((currentAttempt) => __awaiter(this, void 0, void 0, function* () {
                    try {
                        const serverJson = yield loadJsonFile(path.join(store, 'server.json'));
                        logger_1.default.info('A store server has been started. To stop it, use \`pnpm server stop\`');
                        resolve({
                            ctrl: yield server_1.connectStoreController(serverJson.connectionOptions),
                            path: store,
                        });
                        return;
                    }
                    catch (err) {
                        if (!operation.retry(err)) {
                            reject(operation.mainError());
                        }
                    }
                }));
            });
        }
        return yield createStore_1.default(Object.assign(opts, {
            store,
        }));
    });
}
exports.default = default_1;
//# sourceMappingURL=createStoreController.js.map