"use strict";var _WeakMap = require("@babel/runtime-corejs2/core-js/weak-map");var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs2/core-js/object/get-own-property-descriptor");var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");_Object$defineProperty(exports, "__esModule", { value: true });exports.base = base;exports.checkError = checkError;exports.multiConfig = multiConfig;exports.singleConfig = singleConfig;var _assign = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/assign"));var _keys = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/keys"));
var _copyWebpackPlugin = _interopRequireDefault(require("copy-webpack-plugin"));
var _webpackInjectPlugin = _interopRequireWildcard(require("webpack-inject-plugin"));
var _webpackZipPlugin = _interopRequireDefault(require("../plugins/webpack-zip-plugin.js"));
var _webpackMainPlugin = _interopRequireDefault(require("../plugins/webpack-main-plugin.js"));
var _webpackMerge = _interopRequireDefault(require("webpack-merge"));
var _index = require("../../cli-shared-utils/index.js");
var _manifest = require("../lib/manifest.js");
var paths = _interopRequireWildcard(require("../lib/paths.js"));
var _exConfig = _interopRequireDefault(require("../lib/exConfig.js"));
var _constanst = require("../lib/constanst.js");
var _prettyjson = _interopRequireDefault(require("prettyjson"));
var _nodePolyfillWebpackPlugin = _interopRequireDefault(require("node-polyfill-webpack-plugin"));
var _prettyLoader = _interopRequireDefault(require("./pretty-loader"));function _getRequireWildcardCache(e) {if ("function" != typeof _WeakMap) return null;var r = new _WeakMap(),t = new _WeakMap();return (_getRequireWildcardCache = function (e) {return e ? t : r;})(e);}function _interopRequireWildcard(e, r) {if (!r && e && e.__esModule) return e;if (null === e || "object" != typeof e && "function" != typeof e) return { default: e };var t = _getRequireWildcardCache(r);if (t && t.has(e)) return t.get(e);var n = { __proto__: null },a = _Object$defineProperty && _Object$getOwnPropertyDescriptor;for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) {var i = a ? _Object$getOwnPropertyDescriptor(e, u) : null;i && (i.get || i.set) ? _Object$defineProperty(n, u, i) : n[u] = e[u];}return n.default = e, t && t.set(e, n), n;} // import path from 'path'

/**
 * 基于给定的参数生成Webpack配置
 *
 * @param {boolean} isRelease - 是否为发布模式
 * @param {Object} entry - 入口文件配置
 * @param {boolean} amd - 是否支持AMD模块
 * @returns {Object} 生成的Webpack配置对象
 */
function base(isRelease, entry, amd) {
  const ignoreRes = [];

  const webpackConfig = require('./webpack.config');
  const config = (0, _webpackMerge.default)(webpackConfig.default, {
    mode: isRelease ? 'none' : 'development',
    optimization: {
      minimize: false
    },
    devtool: isRelease ? false : 'cheap-module-source-map',
    stats: 'errors-only',
    entry: (0, _assign.default)({
      game: paths.ENTRY
    }, entry),
    plugins: [
    new _nodePolyfillWebpackPlugin.default(),
    new _copyWebpackPlugin.default({
      patterns: [
      {
        from: paths.SRC,
        // 使用 globOptions.ignore 替代旧版 ignore
        globOptions: {
          ignore: [
          // 使用 glob 语法 **/* 匹配所有子目录
          ..._constanst.FILE_EXT_IGNORES.map((ext) => `**/*${ext}`),
          ...ignoreRes.map((pattern) => `**/${pattern}`)]

        },
        // transform 函数保持原有逻辑
        transform(content, path) {
          if (path.includes(_constanst.MANIFEST)) {// 更现代的写法替代 indexOf
            return (0, _manifest.update)({ content, isRelease });
          }
          return content;
        }
      }]

    })]

  });
  // 若amd设置为false，则关闭amd配置，表示不支持amd define转换，默认为true
  if (!amd) {
    config.amd = false;
  }
  // 对小游戏工程目录的webpack配置做postHook处理
  (0, _exConfig.default)(config, {
    context: paths.PROJECT_PATH,
    src: paths.SRC,
    build: paths.BUILD
  });

  return config;
}

/**
 * 原整包打包webpack配置生成
 *
 * @param {string} entry - 入口文件路径
 * @param {boolean} isRelease - 是否为发布模式
 * @param {Object} externals - 外部依赖配置
 * @param {boolean} inject - 是否注入分包模块的依赖
 * @param {boolean} amd - 是否使用AMD模块
 * @returns {Object} 合并后的Webpack配置对象
 */
function singleConfig(entry, isRelease, externals, inject, amd) {
  // 格式化微小相关的代码，便于调试和排查问题
  (0, _prettyLoader.default)(paths.SRC);
  const baseConfig = base(isRelease, entry, amd);
  // 是否注入对分包模块的依赖，如果不注入，由CP用户注入，能力开放给CP用户
  const injectPlugins = inject ? [
  new _webpackInjectPlugin.default(() => {// 打原整包时，通过在主入口 src/game.js 注入其它分包的依赖，并结合externals来实现兼容
    return (0, _keys.default)(externals).reduce((acc, cur) => `require('${cur}');${acc}`, '');
  }, {
    entryName: _constanst.ENTRY_NAME,
    entryOrder: _webpackInjectPlugin.ENTRY_ORDER.Last
  })] : [];

  // const compileStartTime = (new Date()).valueOf()
  return (0, _webpackMerge.default)(baseConfig, {
    externals,
    plugins: [
    new _webpackMainPlugin.default({
      singlePackage: true
    }),
    ...injectPlugins]

  });
}

/**
 * 生成分包的Webpack配置对象
 *
 * @param {string} entry - 入口文件路径
 * @param {boolean} isRelease - 是否为发布版本
 * @param {string} packageName - 包名称
 * @param {Array} externals - 外部依赖
 * @param {Array} subpackages - 子包配置
 * @param {Object} manifest - 清单文件
 * @param {string} buildType - 构建类型
 * @param {boolean} amd - 是否使用AMD模块
 * @returns {Object} 合并后的Webpack配置对象
 */
function multiConfig(entry, isRelease, packageName, externals, subpackages, manifest, buildType, amd) {
  const baseConfig = base(isRelease, entry, amd);
  const compileStartTime = new Date().valueOf();
  return (0, _webpackMerge.default)(baseConfig, {
    externals,
    plugins: [
    new _webpackMainPlugin.default({
      singlePackage: false,
      subpackages
    }),
    new _webpackZipPlugin.default({
      isRelease,
      packageName,
      singlePackage: false, // 打新分包，为false必须提供subpackages
      subpackages,
      manifest,
      buildType,
      compileStartTime
    })]

  });
}
/**
 * 检查webpack编译完成后是否有错误
 * @param {Object} err webpack错误
 * @param {Object} stats 编译状态
 */
function checkError(err, stats) {
  if (err) {// webpack错误，配置文件出错等
    (0, _index.error)(err.stack || err);
    if (err.details) {
      (0, _index.error)(err.details);
    }
    return true;
  }
  const statsJson = stats.toJson();
  if (stats.hasWarnings()) {// 编译警告, 只打印前十个警告
    let warns = statsJson.warnings;
    if (warns.length > 10) {
      warns = warns.splice(0, 10);
      (0, _index.info)('编译结果warnings超过10个，只打印前10个!!!', statsJson.warnings.length);
    }
    const warnings = warns.map((warning) => {
      const { moduleIdentifier, moduleName, loc, message } = warning;
      return { moduleIdentifier, moduleName, loc, message };
    });
    (0, _index.info)(_prettyjson.default.render(warnings));
  }
  if (stats.hasErrors()) {// 编译错误，譬如缺失Module,语法错误等
    const errors = statsJson.errors.map((er) => {
      const { moduleIdentifier, moduleName, loc, message } = er;
      let errMsg = message;
      if (!message) {
        errMsg = er;
      }
      // 找不到模块代码不影响rpk打包
      if (errMsg.includes('Module not found')) {
        const tip = `【不影响rpk打包】请检查对应模块 ${moduleName}下的代码！`;
        (0, _index.info)(_prettyjson.default.render({ moduleIdentifier, moduleName, loc, errMsg, tip }));
      } else {
        return { moduleIdentifier, moduleName, loc, errMsg };
      }
    }).filter(Boolean);
    if (errors.length) {
      (0, _index.error)(_prettyjson.default.render(errors));
      return true;
    }
  }
}