"use strict";

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

function _react() {
  const data = _interopRequireDefault(require("react"));

  _react = function _react() {
    return data;
  };

  return data;
}

function _getUserConfigPlugins() {
  const data = _interopRequireDefault(require("af-webpack/getUserConfigPlugins"));

  _getUserConfigPlugins = function _getUserConfigPlugins() {
    return data;
  };

  return data;
}

function _umiUtils() {
  const data = require("umi-utils");

  _umiUtils = function _umiUtils() {
    return data;
  };

  return data;
}

function _path() {
  const data = require("path");

  _path = function _path() {
    return data;
  };

  return data;
}

function _reactDevUtils() {
  const data = require("af-webpack/react-dev-utils");

  _reactDevUtils = function _reactDevUtils() {
    return data;
  };

  return data;
}

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

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

const plugins = (0, _getUserConfigPlugins().default)();

function noop() {
  return true;
}

const excludes = ['entry', 'outputPath'];

function _default(api) {
  const debug = api.debug,
        cwd = api.cwd,
        config = api.config,
        paths = api.paths; // 把 af-webpack 的配置插件转化为 umi-build-dev 的

  api._registerConfig(() => {
    return plugins.filter(p => !excludes.includes(p.name)).map((_ref) => {
      let name = _ref.name,
          _ref$validate = _ref.validate,
          validate = _ref$validate === void 0 ? noop : _ref$validate,
          extraOpts = _objectWithoutProperties(_ref, ["name", "validate"]);

      return api => _objectSpread({
        name,
        validate,

        onChange(newConfig) {
          try {
            debug(`Config ${name} changed to ${JSON.stringify(newConfig[name])}`);
          } catch (e) {} // eslint-disable-line no-empty


          if (name === 'proxy') {
            global.g_umi_reloadProxy(newConfig[name]);
          } else {
            api.service.restart(`${name} changed`);
          }
        }

      }, extraOpts);
    });
  });

  const reactDir = (0, _umiUtils().compatDirname)('react/package.json', cwd, (0, _path().dirname)(require.resolve('react/package.json')));
  const reactDOMDir = (0, _umiUtils().compatDirname)('react-dom/package.json', cwd, (0, _path().dirname)(require.resolve('react-dom/package.json')));
  const reactRouterDir = (0, _path().dirname)(require.resolve('react-router/package.json'));
  const reactRouterDOMDir = (0, _path().dirname)(require.resolve('react-router-dom/package.json'));
  const reactRouterConfigDir = (0, _path().dirname)(require.resolve('react-router-config/package.json'));
  api.chainWebpackConfig(webpackConfig => {
    webpackConfig.resolve.alias.set('react', reactDir).set('react-dom', reactDOMDir).set('react-router', reactRouterDir).set('react-router-dom', reactRouterDOMDir).set('react-router-config', reactRouterConfigDir).set('history', (0, _umiUtils().compatDirname)('umi-history/package.json', cwd, (0, _path().dirname)(require.resolve('umi-history/package.json')))).set('@', paths.absSrcPath).set('@tmp', paths.absTmpDirPath).set('@@', paths.absTmpDirPath).set('umi', process.env.UMI_DIR);
  });
  /* eslint-disable import/no-dynamic-require */

  api.addVersionInfo([`react@${require((0, _path().join)(reactDir, 'package.json')).version} (${reactDir})`, `react-dom@${require((0, _path().join)(reactDOMDir, 'package.json')).version} (${reactDOMDir})`, `react-router@${require((0, _path().join)(reactRouterDir, 'package.json')).version} (${reactRouterDir})`, `react-router-dom@${require((0, _path().join)(reactRouterDOMDir, 'package.json')).version} (${reactRouterDOMDir})`, `react-router-config@${require((0, _path().join)(reactRouterConfigDir, 'package.json')).version} (${reactRouterConfigDir})`]);
  /* eslint-enable import/no-dynamic-require */

  api.modifyAFWebpackOpts((memo, args = {}) => {
    const ssr = args.ssr;
    const isDev = process.env.NODE_ENV === 'development';
    const entryScript = (0, _path().join)(cwd, `./${paths.tmpDirPath}/umi.js`);
    const setPublicPathFile = (0, _path().join)(__dirname, '../../../template/setPublicPath.js');
    const setPublicPath = config.runtimePublicPath || config.exportStatic && config.exportStatic.dynamicRoot;
    const entry = isDev ? {
      umi: [...(process.env.HMR === 'none' || ssr ? [] : [_reactDevUtils().webpackHotDevClientPath]), ...(setPublicPath ? [setPublicPathFile] : []), entryScript]
    } : {
      umi: [...(setPublicPath ? [setPublicPathFile] : []), entryScript]
    };
    const targets = ssr ? // current running node
    {
      node: true
    } : _objectSpread({
      chrome: 49,
      firefox: 64,
      safari: 10,
      edge: 13,
      ios: 10
    }, config.targets || {}); // Transform targets to browserslist for autoprefixer

    const browserslist = config.browserslist || targets.browsers || Object.keys(targets).filter(key => {
      return !['node', 'esmodules'].includes(key);
    }).map(key => {
      return `${key} >= ${targets[key]}`;
    });
    const plugins = [];

    if (process.env.BABEL_POLYFILL !== 'none') {
      plugins.push(require.resolve('./lockCoreJSVersionPlugin'));
    }

    return _objectSpread({}, memo, {}, config, {
      cwd,
      browserslist,
      entry,
      absNodeModulesPath: paths.absNodeModulesPath,
      outputPath: paths.absOutputPath,
      disableDynamicImport: true,
      extraBabelPlugins: [...(memo.extraBabelPlugins || []), ...(config.extraBabelPlugins || [])],
      babel: config.babel || {
        presets: [[require.resolve('babel-preset-umi'), {
          targets,
          env: ssr ? {} : _objectSpread({
            useBuiltIns: 'entry',
            corejs: 2
          }, config.treeShaking ? {
            modules: false
          } : {})
        }]],
        plugins
      },
      define: _objectSpread({
        'process.env.BASE_URL': config.base || '/',
        __IS_BROWSER: !ssr,
        __UMI_BIGFISH_COMPAT: process.env.BIGFISH_COMPAT,
        __UMI_HTML_SUFFIX: !!(config.exportStatic && typeof config.exportStatic === 'object' && config.exportStatic.htmlSuffix)
      }, config.define || {}),
      publicPath: isDev && !config.ssr ? '/' : config.publicPath != null ? config.publicPath : '/'
    });
  });
}