"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const inquirer_1 = __importDefault(require("inquirer"));
const ora_1 = __importDefault(require("ora"));
const chalk_1 = __importDefault(require("chalk"));
const serialize_javascript_1 = __importDefault(require("serialize-javascript"));
const npm_1 = require("../../utils/npm");
const other_1 = require("../../utils/other");
const beautify_file_1 = require("../../utils/beautify-file");
const doc_1 = require("../../constant/doc");
const cli_1 = require("../../constant/cli");
const npm_2 = require("../../utils/npm");
const array = require('lodash/array');
const fsEx = require('fs-extra');
// 检查上传权限
function checkPermission(npmName) {
    return __awaiter(this, void 0, void 0, function* () {
        const res = yield (0, other_1.spawnPromise)(cli_1.NPM, ['whoami']); // 不用spawnPromise这个方法的话拿不到npm返回值
        if (res.code === 1) {
            console.log(chalk_1.default.red(`请先登录npm账号`));
            return;
        }
        const maintainerName = res.output.replace('\n', '');
        const isMaintainer = yield (0, npm_1.isNpmMaintainer)(npmName, maintainerName);
        if (!isMaintainer) {
            console.log(chalk_1.default.red(`您的账号暂无上传权限。请确认您是否是 ${npmName} 这个npm包的维护者`));
            return false;
        }
        return true;
    });
}
// // 上传文档到oss
// async function uploadOss(npmName) {
//   const distPath = STORYBOOK_DIST_PATH // 文档打包后的产物路径
//   const ossDir = encodeURIComponent(npmName) // 包名需要转义后作为oss存储目录
//   const status = await multipleFilesUpload(ossDir, distPath)
//   if (!status) {
//     return false
//   }
//   console.log('')
//   console.log(
//     chalk.green(`文档访问地址：`),
//     `https://imooc.ifreeovo.xyz/${encodeURIComponent(ossDir)}/index.html`
//   ) // 这里转义是因为阿里云会对oss的存储目录再进行转义，然后生成链接
//   return true
// }
// 重写package.json的files，keywords
function overwritePackageJson(fileContent) {
    return __awaiter(this, void 0, void 0, function* () {
        const { files, keywords } = fileContent;
        if (!files) {
            fileContent.files = [];
        }
        if (!keywords) {
            fileContent.keywords = [];
        }
        const { type } = yield inquirer_1.default.prompt({
            type: 'list',
            name: 'type',
            message: '请选择发布的物料类型',
            choices: cli_1.MATERIAL_TYPE,
        });
        fileContent.files = array.union(fileContent.files, ['.arkdoc-dist']); // 利用lodash数组去重
        fileContent.keywords = array.union(fileContent.keywords, [
            `name=arkdoc&type=${type}`,
        ]);
        const content = (0, beautify_file_1.beautifyJs)((0, serialize_javascript_1.default)(fileContent, {
            unsafe: true,
        }));
        fsEx.writeFileSync(cli_1.PROJECT_PACKAGE_JSON_PATH, content);
    });
}
function publishDoc() {
    return __awaiter(this, void 0, void 0, function* () {
        const { isPublish } = yield inquirer_1.default.prompt({
            type: 'confirm',
            name: 'isPublish',
            message: '请确认是否发布文档',
        });
        if (isPublish) {
            if (!fsEx.pathExistsSync(doc_1.PROJECT_DOC_DIST_PATH)) {
                console.log(chalk_1.default.red('未找到打包文件，请先执行npm bulish --doc进行打包'));
                return;
            }
            const spinner = (0, ora_1.default)('正在检查账号是否有发布权限，请稍等...').start();
            spinner.text = '';
            console.log('');
            // 使用npm命令判断用户是否登录
            // 验证登录用户是否是npm包的所有者，是的话才有上传权限
            if (!fsEx.pathExistsSync(cli_1.PROJECT_PACKAGE_JSON_PATH)) {
                spinner.fail(chalk_1.default.red('当前路径下未找到package.json。请确认命令执行路径是否正确!'));
                return;
            }
            const file = require(cli_1.PROJECT_PACKAGE_JSON_PATH);
            const { name, version } = file;
            const isValid = yield checkPermission(name);
            if (!isValid) {
                spinner.stop();
                return;
            }
            // 上传文档到oss
            spinner.text = '权限检查通过。';
            yield (0, other_1.sleep)(); // 防止spinner.text覆盖掉上一次的spinner.text显示
            console.log('');
            // 重写package.json的files，keywords
            spinner.stop();
            yield overwritePackageJson(file);
            spinner.start('正在上传文档资源，请稍等...');
            yield (0, other_1.sleep)();
            console.log('');
            const { status } = (yield (0, npm_2.npm)(['publish']));
            if (status !== 0) {
                spinner.fail(chalk_1.default.red('文档上传失败!'));
                return;
            }
            console.log('');
            console.log(chalk_1.default.green(`文档访问地址：`), `https://unpkg.com/${name}@${version}/.arkdoc-dist/index.html`);
            console.log('');
            spinner.succeed(chalk_1.default.green('文档上传成功!'));
        }
    });
}
exports.default = publishDoc;
//# sourceMappingURL=data:application/json;base64, 