import { readEnvVariable } from './env-variable.mjs';
import { writeFileSync } from '../fs/fs.mjs';
import { getPath } from '../nodejs/path.mjs';
import '../nodejs/fs.mjs';
import '../nodejs/crypto.mjs';
import '../nodejs/os.mjs';

var npmTokenRoot = process.cwd();
function getNpmToken() {
  var NPM_TOKEN = 'NPM_TOKEN';
  var ENV_FILE = '.env.local';
  var envFile = getPath().resolve(npmTokenRoot, ENV_FILE);
  var token = readEnvVariable(NPM_TOKEN, envFile);
  if (!token) {
    console.log("".concat(NPM_TOKEN, " \u4E0D\u5B58\u5728"));
    process.exit(1);
  }
  return token;
}
/**
 * 将 .env.local 中 NPM_TOKEN 的值写入到 .npmrc 中
 * @example
 * ```ts
 * // 在发版脚本中使用：
 * // 先在项目根目录的 .env.local 写入 NPM_TOKEN=xxx
 * // 然后调用此方法生成 .npmrc，便于 npm publish 进行授权
 * writeEnvTokenToNpmRC();
 * ```
 */
function writeEnvTokenToNpmRC() {
  var NPM_RC_TPL = "registry=https://registry.npmjs.org/\n//registry.npmjs.org/:always-auth=true\n//registry.npmjs.org/:_authToken={{TOKEN}}";
  var token = getNpmToken();
  var content = NPM_RC_TPL.replace('{{TOKEN}}', token);
  var npmRCFile = getPath().resolve(npmTokenRoot, '.npmrc');
  writeFileSync(npmRCFile, content);
}

export { writeEnvTokenToNpmRC };
