"use strict";

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

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

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

  return data;
}

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

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

  return data;
}

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

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

  return data;
}

function _lodash() {
  const data = require("lodash");

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

  return data;
}

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

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(n); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

let targetLevel = null;
let level = 0;

var _default = (routes, service) => {
  if (process.env.CODE_SPLITTING_LEVEL) {
    targetLevel = process.env.CODE_SPLITTING_LEVEL;
  } else {
    targetLevel = 1;
    const routesHaveChild = routes.filter(route => route.routes && route.routes.length);

    if (routesHaveChild.length) {
      targetLevel = 2;
    }
  }

  const applyPlugins = service.applyPlugins,
        paths = service.paths;
  const clonedRoutes = (0, _lodash().cloneDeep)(routes);
  patchRoutes(clonedRoutes);
  return JSON.stringify(clonedRoutes, (key, value) => {
    switch (key) {
      case 'component':
        {
          if (value.startsWith('() =>')) {
            return value;
          }

          const _value$split = value.split('^^'),
                _value$split2 = _slicedToArray(_value$split, 2),
                component = _value$split2[0],
                webpackChunkName = _value$split2[1];

          const importPath = (0, _path().isAbsolute)(component) ? component : (0, _umiUtils().winPath)((0, _path().relative)(paths.tmpDirPath, component));
          let ret = `require('${importPath}').default`;

          if (applyPlugins) {
            ret = applyPlugins.call(service, 'modifyRouteComponent', {
              initialValue: ret,
              args: {
                importPath,
                webpackChunkName,
                component
              }
            });
          }

          return ret;
        }

      case 'Routes':
        return `[${value.map(v => `require('${(0, _umiUtils().winPath)(precedingDot((0, _path().relative)(paths.absTmpDirPath, (0, _path().join)(paths.cwd, v))))}').default`).join(', ')}]`;

      default:
        return value;
    }
  }, 2);
};

exports.default = _default;

function patchRoutes(routes, webpackChunkName) {
  level += 1;
  routes.forEach(route => {
    patchRoute(route, webpackChunkName);
  });
  level -= 1;
}

function precedingDot(p) {
  return p.startsWith('.') ? p : `./${p}`;
}

function normalizeEntry(entry) {
  return entry.replace(/^.(\/|\\)/, '').replace(/(\/|\\)/g, '__').replace(/\.jsx?$/, '').replace(/\.tsx?$/, '');
}

function patchRoute(route, webpackChunkName) {
  if (route.component && !route.component.startsWith('() =>')) {
    if (!webpackChunkName || level <= targetLevel) {
      webpackChunkName = normalizeEntry(route.component || 'common_component').replace(/^src__/, '').replace(/^pages__/, 'p__').replace(/^page__/, 'p__').replace(/\$/g, '_');
    }

    route.component = [route.component || 'common_component', webpackChunkName, route.path].join('^^');
  }

  if (route.routes) {
    // 只在一级路由做按需编译
    patchRoutes(route.routes, webpackChunkName);
  }
}