"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.defaulter = exports.default = void 0;

var _child_process = require("child_process");

var _fs = _interopRequireWildcard(require("fs"));

var _path = _interopRequireDefault(require("path"));

var _schemas = _interopRequireDefault(require("../schemas"));

var _deprecationSupport = require("./deprecationSupport");

var _deprecationLogger = require("../deprecationLogger");

var _logger = require("../logger");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

// import { argv } from 'process';
const args = process.argv.slice(2); // console.log('argv', argv);

const NPM_CONFIG_PREFIX = 'npm_config_'; // TODO: we have to do option parse logic little better
// if user use react-cli stritly without using npm scripts options won't work,
//  So  we have to write our own option parse logic or some other library
// console.log('type', process.argv,  process.env.npm_config_check,  process.env.npm_config_clone_type, process.env.npm_config_clone_url);
// console.log('Object.keys(process.env).filter(s => s.startsWith(\'npm_config_\') && s.includes(\'clone\')', Object.keys(process.env).filter(s => s.startsWith('npm_config_') && s.includes('clone')));
// // clone:type

const processEnv = {};
const keysWithColon = [];
Object.keys(process.env).filter(key => key.startsWith(NPM_CONFIG_PREFIX)).forEach(key => {
  const nkey = key.slice(NPM_CONFIG_PREFIX.length);
  processEnv[nkey] = process.env[key];
  nkey.includes(':') && keysWithColon.push(nkey);
});
keysWithColon.forEach(key => {
  const nkey = key.replace(/:/g, '_');

  if (processEnv[nkey]) {
    throw Error('there is some options conflict', key, nkey);
  }

  processEnv[nkey] = processEnv[key];
});

function getNpmVersion() {
  // require("child_process").
  let vers = '6';

  try {
    [vers] = (0, _child_process.execSync)('npm -v').toString().trim().split('.');
  } catch (error) {
    console.log(error);
  }

  return vers;
}

function getCWD() {
  // require("child_process").
  let cwd = process.cwd();

  try {
    const ress = (0, _child_process.execSync)('npm bin').toString();
    const i = ress.lastIndexOf('node_modules');
    cwd = i === -1 ? cwd : ress.slice(0, i);
  } catch (error) {
    console.log(error);
  }

  return cwd;
} // experimental argumnet parsing logic


args.forEach(option => {
  if (/^--./.test(option)) {
    const equIndex = option.indexOf('='); // equIndex = equIndex === -1 ? option.length : equIndex;

    let key = option.slice(2, equIndex);
    let value = option.slice(equIndex + 1);

    if (equIndex === -1) {
      key = option.slice(2);
      value = true;
    }

    key = key.replace(/-|:/g, '_');
    processEnv[key] = value;
  }
});

const defaulter = (target, source) => {
  const defaultObject = {};
  Object.keys(target).forEach(key => {
    const data = target[key];

    if (data && typeof data === 'object') {
      if (Array.isArray(data)) {
        defaultObject[key] = source[key] || data;
      } else if (typeof data.cli === 'string') {
        let cliData;

        if (typeof processEnv[data.cli] === 'string') {
          cliData = processEnv[data.cli];
        } else if (typeof processEnv[data.cli.toLowerCase()] === 'string') {
          cliData = processEnv[data.cli.toLowerCase()];
        } else {
          cliData = source && source[key] || data.value;
        }

        if (typeof data.value === 'boolean') {
          cliData = cliData === 'true' || cliData === true ? true : cliData === 'false' || cliData === false || cliData === '' ? false : data.value;
        }

        defaultObject[key] = cliData;
      } else {
        defaultObject[key] = defaulter(data, source && source[key] ? source[key] : Array.isArray(target[key]) ? [] : {});
      }
    } else {
      defaultObject[key] = typeof source === 'object' && source[key] !== null && typeof source[key] !== 'undefined' ? source[key] : target[key];
    }
  });
  return defaultObject;
};

exports.defaulter = defaulter;
global.reactCLIOptions = null;

const getOptionsFromConfigFile = (appPath, configFileName) => {
  const fileName = configFileName || 'react-cli.config.js';

  if (!configFileName) {
    (0, _logger.verboseLogger)('we have used default react-cli.config.js');
  }

  const packagePath = _path.default.join(appPath, fileName);

  if ((0, _fs.existsSync)(packagePath)) {
    return require(packagePath).config;
  }

  const oldDeprecatedConfigFilePath = _path.default.join(appPath, 'build.config.js');

  if ((0, _fs.existsSync)(oldDeprecatedConfigFilePath)) {
    (0, _deprecationLogger.deprecateMessage)('"build.config.js" file was deprecated. So Kindly rename it as "react-cli.config.js"');
    return require(oldDeprecatedConfigFilePath).config;
  }

  return null;
};

const getOptions = fromRoot => {
  if (global.reactCLIOptions) {
    return global.reactCLIOptions;
  }

  const appPath = process.cwd();
  let userSchemas = getOptionsFromConfigFile(appPath, processEnv.config_file);

  const packagePath = _path.default.join(appPath, 'package.json');

  if (_fs.default.existsSync(packagePath)) {
    userSchemas = userSchemas || require(packagePath)['react-cli'] || {};
  }

  const options = defaulter(_schemas.default, userSchemas || {}); // for future may be for npm 8 edge cases

  options.npmVersion = getNpmVersion();
  options.cwd = getCWD();
  (0, _deprecationSupport.deprecationSupport)(options, options.disableDeprecationWarning || !fromRoot);
  options.packageVersion = process.env.npm_package_version;
  global.reactCLIOptions = options;
  return options;
};

var _default = getOptions;
exports.default = _default;