import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';

/**
 * 将嵌套的组件依赖关系打平为一维映射
 * 递归遍历组件依赖树，将每个页面/组件的所有直接和间接依赖打平为数组
 * @param {Record<string, any>} rawMap 原始组件依赖映射，key 为页面/组件名，value 为其直接依赖的组件映射
 * @returns {ComponentMapList} 打平后的组件列表映射，key 为页面/组件名，value 为所有依赖组件名数组
 * @example
 * ```ts
 * const rawMap = {
 *   'pages/index': { 'comp-a': true, 'comp-b': true },
 *   'comp-a': { 'comp-c': true },
 * };
 * const result = flattenUsingComponentMap(rawMap);
 * // { 'pages/index': ['comp-a', 'comp-b', 'comp-c'], 'comp-a': ['comp-c'] }
 * ```
 */
function flattenUsingComponentMap(rawMap) {
  var res = {};
  function cursive() {
    var componentsMap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    var components = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
    var fathers = arguments.length > 2 ? arguments[2] : undefined;
    var keys = Object.keys(componentsMap);
    for (var _i = 0, _keys = keys; _i < _keys.length; _i++) {
      var key = _keys[_i];
      if (fathers.includes(key)) {
        // 防止递归调用，即防止子孙和祖先相同
        continue;
      }
      var subComponentsMap = rawMap[key];
      if (subComponentsMap) {
        var innerKeys = Object.keys(subComponentsMap);
        innerKeys.forEach(function (innerKey) {
          if (!fathers.includes(innerKey)) {
            // 防止递归调用
            components.push(innerKey);
          }
        });
        cursive(subComponentsMap, components, [].concat(_toConsumableArray(fathers), [key]));
      }
    }
  }
  Object.keys(rawMap).map(function (key) {
    var components = [];
    var componentsMap = rawMap[key];
    if (componentsMap) {
      var _components;
      (_components = components).push.apply(_components, _toConsumableArray(Object.keys(componentsMap)));
      components = Array.from(new Set(components));
    }
    cursive(componentsMap, components, [key]);
    res[key] = components;
  });
  return res;
}

export { flattenUsingComponentMap };
