"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var config_exports = {};
__export(config_exports, {
  chainStaticAssetRule: () => chainStaticAssetRule,
  getDefaultDevConfig: () => getDefaultDevConfig,
  getDefaultHtmlConfig: () => getDefaultHtmlConfig,
  getDefaultOutputConfig: () => getDefaultOutputConfig,
  getDefaultPerformanceConfig: () => getDefaultPerformanceConfig,
  getDefaultSecurityConfig: () => getDefaultSecurityConfig,
  getDefaultSourceConfig: () => getDefaultSourceConfig,
  getDefaultStyledComponentsConfig: () => getDefaultStyledComponentsConfig,
  getDefaultToolsConfig: () => getDefaultToolsConfig,
  getExtensions: () => getExtensions,
  getMinify: () => getMinify,
  outputInspectConfigFiles: () => outputInspectConfigFiles,
  pickRsbuildConfig: () => pickRsbuildConfig,
  setConfig: () => setConfig,
  stringifyConfig: () => stringifyConfig
});
module.exports = __toCommonJS(config_exports);
var import_constants = require("./constants");
var import_pick = require("./pick");
var import_rslog = require("rslog");
var import_path = require("path");
var import_color = require("./color");
var import_fs_extra = __toESM(require("../compiled/fs-extra"));
var import_lodash = __toESM(require("lodash"));
var import_constants2 = require("./constants");
var import_minimize = require("./minimize");
const getDefaultDevConfig = () => ({
  hmr: true,
  https: false,
  port: import_constants.DEFAULT_PORT,
  assetPrefix: import_constants.DEFAULT_ASSET_PREFIX,
  startUrl: false,
  host: import_constants2.DEFAULT_DEV_HOST
});
const getDefaultSourceConfig = () => ({
  alias: {},
  define: {},
  aliasStrategy: "prefer-tsconfig",
  preEntry: []
});
const getDefaultHtmlConfig = () => ({
  meta: {
    charset: { charset: "UTF-8" },
    viewport: "width=device-width, initial-scale=1.0"
  },
  title: "Rsbuild App",
  inject: "head",
  mountId: import_constants.DEFAULT_MOUNT_ID,
  crossorigin: false,
  outputStructure: "flat",
  scriptLoading: "defer"
});
const getDefaultSecurityConfig = () => ({
  nonce: ""
});
const getDefaultToolsConfig = () => ({});
const getDefaultPerformanceConfig = () => ({
  profile: false,
  buildCache: true,
  printFileSize: true,
  removeConsole: false,
  transformLodash: true,
  removeMomentLocale: false,
  chunkSplit: {
    strategy: "split-by-experience"
  }
});
const getDefaultOutputConfig = () => ({
  distPath: {
    root: import_constants.ROOT_DIST_DIR,
    js: import_constants.JS_DIST_DIR,
    css: import_constants.CSS_DIST_DIR,
    svg: import_constants.SVG_DIST_DIR,
    font: import_constants.FONT_DIST_DIR,
    html: import_constants.HTML_DIST_DIR,
    wasm: import_constants.WASM_DIST_DIR,
    image: import_constants.IMAGE_DIST_DIR,
    media: import_constants.MEDIA_DIST_DIR,
    server: import_constants.SERVER_DIST_DIR,
    worker: import_constants.SERVER_WORKER_DIST_DIR
  },
  assetPrefix: import_constants.DEFAULT_ASSET_PREFIX,
  filename: {},
  charset: "ascii",
  polyfill: "usage",
  dataUriLimit: {
    svg: import_constants.DEFAULT_DATA_URL_SIZE,
    font: import_constants.DEFAULT_DATA_URL_SIZE,
    image: import_constants.DEFAULT_DATA_URL_SIZE,
    media: import_constants.DEFAULT_DATA_URL_SIZE
  },
  legalComments: "linked",
  cleanDistPath: true,
  disableCssExtract: false,
  disableMinimize: false,
  disableSourceMap: {
    js: false,
    css: void 0
  },
  disableFilenameHash: false,
  disableCssModuleExtension: false,
  enableAssetFallback: false,
  enableLatestDecorators: false,
  enableCssModuleTSDeclaration: false,
  enableInlineScripts: false,
  enableInlineStyles: false,
  cssModules: {
    exportLocalsConvention: "camelCase"
  }
});
async function outputInspectConfigFiles({
  rsbuildConfig,
  bundlerConfigs,
  inspectOptions,
  rsbuildOptions,
  configType
}) {
  const { outputPath } = inspectOptions;
  const { target } = rsbuildOptions;
  const files = [
    {
      path: (0, import_path.join)(outputPath, "rsbuild.config.js"),
      label: "Rsbuild Config",
      content: rsbuildConfig
    },
    ...bundlerConfigs.map((content, index) => {
      const suffix = Array.isArray(target) ? target[index] : target;
      const outputFile = `${configType}.config.${suffix}.js`;
      let outputFilePath = (0, import_path.join)(outputPath, outputFile);
      if (import_fs_extra.default.existsSync(outputFilePath)) {
        outputFilePath = outputFilePath.replace(/\.js$/, `.${Date.now()}.js`);
      }
      return {
        path: outputFilePath,
        label: `${import_lodash.default.upperFirst(configType)} Config (${suffix})`,
        content
      };
    })
  ];
  await Promise.all(
    files.map(
      (item) => import_fs_extra.default.outputFile(item.path, `module.exports = ${item.content}`)
    )
  );
  const fileInfos = files.map(
    (item) => `  - ${import_color.color.bold(import_color.color.yellow(item.label))}: ${import_color.color.underline(
      item.path
    )}`
  ).join("\n");
  import_rslog.logger.success(
    `Inspect config succeed, open following files to view the content: 

${fileInfos}
`
  );
}
const setConfig = (config, path, value) => {
  import_lodash.default.set(config, path, value);
};
function getExtensions({
  target = "web",
  resolveExtensionPrefix,
  isTsProject
} = {}) {
  let extensions = [
    // only resolve .ts(x) files if it's a ts project
    // most projects are using TypeScript, resolve .ts(x) files first to reduce resolve time.
    ...isTsProject ? [".ts", ".tsx"] : [],
    ".js",
    ".jsx",
    ".mjs",
    ".json"
  ];
  if (resolveExtensionPrefix) {
    const extensionPrefix = typeof resolveExtensionPrefix === "string" ? resolveExtensionPrefix : resolveExtensionPrefix[target];
    if (extensionPrefix) {
      extensions = extensions.reduce(
        (ret, ext) => [...ret, extensionPrefix + ext, ext],
        []
      );
    }
  }
  return extensions;
}
async function getMinify(isProd, config) {
  if (config.output.disableMinimize || !isProd) {
    return false;
  }
  const minifyJS = (await (0, import_minimize.getJSMinifyOptions)(config)).terserOptions;
  return {
    removeComments: false,
    useShortDoctype: true,
    keepClosingSlash: true,
    collapseWhitespace: true,
    removeRedundantAttributes: true,
    removeScriptTypeAttributes: true,
    removeStyleLinkTypeAttributes: true,
    removeEmptyAttributes: true,
    minifyJS,
    minifyCSS: true,
    minifyURLs: true
  };
}
async function stringifyConfig(config, verbose) {
  const { default: WebpackChain } = await Promise.resolve().then(() => __toESM(require("../compiled/webpack-chain")));
  const stringify = WebpackChain.toString;
  return stringify(config, { verbose });
}
const chainStaticAssetRule = ({
  rule,
  maxSize,
  filename,
  assetType,
  issuer
}) => {
  rule.oneOf(`${assetType}-asset-url`).type("asset/resource").resourceQuery(/(__inline=false|url)/).set("generator", {
    filename
  }).set("issuer", issuer);
  rule.oneOf(`${assetType}-asset-inline`).type("asset/inline").resourceQuery(/inline/).set("issuer", issuer);
  rule.oneOf(`${assetType}-asset`).type("asset").parser({
    dataUrlCondition: {
      maxSize
    }
  }).set("generator", {
    filename
  }).set("issuer", issuer);
};
const getDefaultStyledComponentsConfig = (isProd, ssr) => {
  return {
    ssr,
    // "pure" is used to improve dead code elimination in production.
    // we don't need to enable it in development because it will slow down the build process.
    pure: isProd,
    displayName: true,
    transpileTemplateLiterals: true
  };
};
const pickRsbuildConfig = (rsbuildConfig) => {
  const keys = [
    "dev",
    "html",
    "tools",
    "source",
    "output",
    "security",
    "performance"
  ];
  return (0, import_pick.pick)(rsbuildConfig, keys);
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  chainStaticAssetRule,
  getDefaultDevConfig,
  getDefaultHtmlConfig,
  getDefaultOutputConfig,
  getDefaultPerformanceConfig,
  getDefaultSecurityConfig,
  getDefaultSourceConfig,
  getDefaultStyledComponentsConfig,
  getDefaultToolsConfig,
  getExtensions,
  getMinify,
  outputInspectConfigFiles,
  pickRsbuildConfig,
  setConfig,
  stringifyConfig
});
