text: "use strict";
  
  Object.defineProperty(exports, "__esModule", {
    value: true
  });
  exports.getModel = getModel;
  exports.getGlobalModels = getGlobalModels;
  exports.default = _default;
  
  var _fs = require("fs");
  
  var _path = require("path");
  
  var _globby = _interopRequireDefault(require("globby"));
  
  var _lodash = _interopRequireDefault(require("lodash.uniq"));
  
  var _pathIsRoot = _interopRequireDefault(require("path-is-root"));
  
  var _slash = _interopRequireDefault(require("slash2"));
  
  var _utils = require("./utils");
  
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, 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 getModel(cwd, service) {
    const config = service.config;
    const modelJSPath = (0, _utils.findJSFile)(cwd, 'model');
  
    if (modelJSPath) {
      return [(0, _slash.default)(modelJSPath)];
    }
  
    return _globby.default.sync(`./${config.singular ? 'model' : 'models'}/**/*.{ts,tsx,js,jsx}`, {
      cwd
    }).filter(p => !p.endsWith('.d.ts') && !p.endsWith('.test.js') && !p.endsWith('.test.jsx') && !p.endsWith('.test.ts') && !p.endsWith('.test.tsx')).map(p => (0, _slash.default)((0, _path.join)(cwd, p)));
  }
  
  function getModelsWithRoutes(routes, service) {
    const paths = service.paths;
    return routes.reduce((memo, route) => {
      if (route.component) {
        return [...memo, ...getPageModels((0, _path.join)(paths.cwd, route.component), service), ...(route.routes ? getModelsWithRoutes(route.routes, service) : [])];
      } else {
        return memo;
      }
    }, []);
  }
  
  function getPageModels(cwd, service) {
    let models = [];
  
    while (!isPagesPath(cwd, service) && !isSrcPath(cwd, service) && !(0, _pathIsRoot.default)(cwd)) {
      models = models.concat(getModel(cwd, service));
      cwd = (0, _path.dirname)(cwd);
    }
  
    return models;
  }
  
  function isPagesPath(path, service) {
    const paths = service.paths;
    return (0, _utils.endWithSlash)((0, _slash.default)(path)) === (0, _utils.endWithSlash)((0, _slash.default)(paths.absPagesPath));
  }
  
  function isSrcPath(path, service) {
    const paths = service.paths;
    return (0, _utils.endWithSlash)((0, _slash.default)(path)) === (0, _utils.endWithSlash)((0, _slash.default)(paths.absSrcPath));
  }
  
  function getGlobalModels(service, shouldImportDynamic) {
    const paths = service.paths,
          routes = service.routes;
    let models = getModel(paths.absSrcPath, service);
  
    if (!shouldImportDynamic) {
      // 不做按需加载时，还需要额外载入 page 路由的 models 文件
      models = [...models, ...getModelsWithRoutes(routes, service)]; // 去重
  
      models = (0, _lodash.default)(models);
    }
  
    return models;
  }
  
  function _default(api, opts = {}) {
    const _api$placeholder = api.placeholder,
          RENDER = _api$placeholder.RENDER,
          ROUTER_MODIFIER = _api$placeholder.ROUTER_MODIFIER,
          IMPORT = _api$placeholder.IMPORT;
    const _api$service = api.service,
          paths = _api$service.paths,
          config = _api$service.config;
    const dvaContainerPath = (0, _path.join)(paths.absTmpDirPath, 'DvaContainer.js');
    const isProduction = process.env.NODE_ENV === 'production';
    const shouldImportDynamic = isProduction && !config.disableDynamicImport;
  
    function getDvaJS() {
      const dvaJS = (0, _utils.findJSFile)(paths.absSrcPath, 'dva');
  
      if (dvaJS) {
        return (0, _slash.default)(dvaJS);
      }
    }
  
    function getModelName(model) {
      const modelArr = (0, _slash.default)(model).split('/');
      return modelArr[modelArr.length - 1];
    }
  
    function exclude(models, excludes) {
      return models.filter(model => {
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;
  
        try {
          for (var _iterator = excludes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            const exclude = _step.value;
  
            if (typeof exclude === 'function' && exclude(getModelName(model))) {
              return false;
            }
  
            if (exclude instanceof RegExp && exclude.test(getModelName(model))) {
              return false;
            }
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
              _iterator.return();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }
  
        return true;
      });
    }
  
    function getGlobalModelContent() {
      return exclude(getGlobalModels(api.service, shouldImportDynamic), (0, _utils.optsToArray)(opts.exclude)).map(path => `
      app.model({ namespace: '${(0, _path.basename)(path, (0, _path.extname)(path))}', ...(require('${path}').default) });
    `.trim()).join('\r\n');
    }
  
    function getPluginContent() {
      const pluginPaths = _globby.default.sync('plugins/**/*.{js,ts}', {
        cwd: paths.absSrcPath
      });
  
      const ret = pluginPaths.map(path => `
  app.use(require('../../${path}').default);
    `.trim());
  
      if (opts.immer) {
        ret.push(`
  app.use(require('${(0, _slash.default)(require.resolve('dva-immer'))}').default());
        `.trim());
      }
  
      return ret.join('\r\n');
    }
  
    api.register('generateFiles', () => {
      const tpl = (0, _path.join)(__dirname, '../template/DvaContainer.js');
      let tplContent = (0, _fs.readFileSync)(tpl, 'utf-8');
      const dvaJS = getDvaJS();
  
      if (dvaJS) {
        tplContent = tplContent.replace('<%= ExtendDvaConfig %>', `
  ...((require('${dvaJS}').config || (() => ({})))()),
          `.trim()); //         .replace('<%= EnhanceApp %>', `
        // app = (require('${dvaJS}').enhance || (app => app))(app);
        //         `.trim());
      }
  
      tplContent = tplContent.replace('<%= ExtendDvaConfig %>', '').replace('<%= EnhanceApp %>', '').replace('<%= RegisterPlugins %>', getPluginContent()).replace('<%= RegisterModels %>', getGlobalModelContent());
      (0, _fs.writeFileSync)(dvaContainerPath, tplContent, 'utf-8');
    });
    api.register('modifyRouterFile', ({
      memo
    }) => {
      return memo.replace(IMPORT, `
  import { routerRedux } from 'dva/router';
  ${shouldImportDynamic ? `import _dvaDynamic from 'dva/dynamic';` : ''}
  ${IMPORT}
        `.trim()).replace(ROUTER_MODIFIER, `
  const { ConnectedRouter } = routerRedux;
  Router = ConnectedRouter;
  ${ROUTER_MODIFIER}
        `.trim());
    });
  
    if (shouldImportDynamic) {
      api.register('modifyRouteComponent', ({
        memo,
        args
      }) => {
        const pageJSFile = args.pageJSFile,
              webpackChunkName = args.webpackChunkName;
  
        if (!webpackChunkName) {
          return memo;
        }
  
        const loading = config.loading;
        let loadingOpts = '';
  
        if (loading) {
          loadingOpts = `LoadingComponent: require('${(0, _slash.default)((0, _path.join)(paths.cwd, loading))}').default,`;
        }
  
        let ret = `
  _dvaDynamic({
    <%= MODELS %>
    component: () => import(/* webpackChunkName: '${webpackChunkName}' */'${pageJSFile}'),
    ${loadingOpts}
  })
        `.trim();
        const models = getPageModels((0, _path.join)(paths.absTmpDirPath, pageJSFile), api.service);
  
        if (models && models.length) {
          ret = ret.replace('<%= MODELS %>', `
  app: window.g_app,
  models: () => [
    ${models.map(model => `import(/* webpackChunkName: '${(0, _utils.chunkName)(paths.cwd, model)}' */'${model}')`).join(',\r\n  ')}
  ],
        `.trim());
        }
  
        return ret.replace('<%= MODELS %>', '');
      });
    }
  
    api.register('modifyEntryFile', ({
      memo
    }) => {
      const dvaRender = api.service.applyPlugins('modifyDvaRender', {
        initialValue: `
  ReactDOM.render(React.createElement(
    DvaContainer,
    null,
    React.createElement(require('./router').default)
  ), document.getElementById('root'));
  `.trim()
      });
      return memo.replace(RENDER, `
  const DvaContainer = require('./DvaContainer').default;
  ${dvaRender}
  `.trim());
    });
    api.register('modifyAFWebpackOpts', ({
      memo
    }) => {
      memo.alias = _objectSpread({}, memo.alias, {
        dva: (0, _path.dirname)(require.resolve('dva/package')),
        'dva-loading': require.resolve('dva-loading'),
        'path-to-regexp': require.resolve('path-to-regexp'),
        'object-assign': require.resolve('object-assign')
      }, opts.immer ? {
        immer: require.resolve('immer')
      } : {});
      return memo;
    });
    api.register('modifyPageWatchers', ({
      memo
    }) => {
      return [...memo, (0, _path.join)(paths.absSrcPath, 'models'), (0, _path.join)(paths.absSrcPath, 'plugins'), (0, _path.join)(paths.absSrcPath, 'model.js'), (0, _path.join)(paths.absSrcPath, 'model.jsx'), (0, _path.join)(paths.absSrcPath, 'model.ts'), (0, _path.join)(paths.absSrcPath, 'model.tsx'), (0, _path.join)(paths.absSrcPath, 'dva.js'), (0, _path.join)(paths.absSrcPath, 'dva.jsx'), (0, _path.join)(paths.absSrcPath, 'dva.ts'), (0, _path.join)(paths.absSrcPath, 'dva.tsx')];
    });
  }