"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isUseCssExtract = exports.getCssLoaderOptions = exports.normalizeCssLoaderOptions = exports.getPostcssConfig = exports.getCssnanoDefaultOptions = exports.getCssModulesAutoRule = exports.isCssModules = exports.isLooseCssModules = exports.getCssModuleLocalIdentName = void 0;
const assert_1 = __importDefault(require("assert"));
const constants_1 = require("./constants");
const lodash_1 = require("@modern-js/utils/lodash");
const getCssSupport_1 = require("./getCssSupport");
const utils_1 = require("./utils");
const getCssModuleLocalIdentName = (config, isProd) => config.output.cssModuleLocalIdentName ||
    // Using shorter classname in production to reduce bundle size
    (isProd ? '[hash:base64:5]' : '[path][name]__[local]--[hash:base64:5]');
exports.getCssModuleLocalIdentName = getCssModuleLocalIdentName;
/** Determine if a file path is a CSS module when disableCssModuleExtension is enabled. */
const isLooseCssModules = (path) => {
    if (constants_1.NODE_MODULES_REGEX.test(path)) {
        return constants_1.CSS_MODULES_REGEX.test(path);
    }
    return !constants_1.GLOBAL_CSS_REGEX.test(path);
};
exports.isLooseCssModules = isLooseCssModules;
const isCssModules = (filename, modules) => {
    if (typeof modules === 'boolean') {
        return modules;
    }
    // todo: this configuration is not common and more complex.
    if (typeof modules === 'string') {
        return true;
    }
    const { auto } = modules;
    if (typeof auto === 'boolean') {
        return auto && constants_1.CSS_MODULES_REGEX.test(filename);
    }
    else if (auto instanceof RegExp) {
        return auto.test(filename);
    }
    else if (typeof auto === 'function') {
        return auto(filename);
    }
    return true;
};
exports.isCssModules = isCssModules;
const getCssModulesAutoRule = (config, disableCssModuleExtension = false) => {
    if (!config || (config === null || config === void 0 ? void 0 : config.auto) === undefined) {
        return disableCssModuleExtension ? exports.isLooseCssModules : true;
    }
    return config.auto;
};
exports.getCssModulesAutoRule = getCssModulesAutoRule;
const getCssnanoDefaultOptions = () => ({
    preset: [
        'default',
        {
            // merge longhand will break safe-area-inset-top, so disable it
            // https://github.com/cssnano/cssnano/issues/803
            // https://github.com/cssnano/cssnano/issues/967
            mergeLonghand: false,
        },
    ],
});
exports.getCssnanoDefaultOptions = getCssnanoDefaultOptions;
const getPostcssConfig = async ({ enableCssMinify, enableSourceMap, browserslist, config, }) => {
    const { applyOptionsChain } = await Promise.resolve().then(() => __importStar(require('@modern-js/utils')));
    const extraPlugins = [];
    const utils = {
        addPlugins(plugins) {
            if (Array.isArray(plugins)) {
                extraPlugins.push(...plugins);
            }
            else {
                extraPlugins.push(plugins);
            }
        },
    };
    const cssSupport = (0, getCssSupport_1.getCssSupport)(browserslist);
    const mergedConfig = applyOptionsChain({
        postcssOptions: {
            plugins: [
                require((0, utils_1.getSharedPkgCompiledPath)('postcss-flexbugs-fixes')),
                !cssSupport.customProperties &&
                    require((0, utils_1.getSharedPkgCompiledPath)('postcss-custom-properties')),
                !cssSupport.initial && require((0, utils_1.getSharedPkgCompiledPath)('postcss-initial')),
                !cssSupport.pageBreak &&
                    require((0, utils_1.getSharedPkgCompiledPath)('postcss-page-break')),
                !cssSupport.fontVariant &&
                    require((0, utils_1.getSharedPkgCompiledPath)('postcss-font-variant')),
                !cssSupport.mediaMinmax &&
                    require((0, utils_1.getSharedPkgCompiledPath)('postcss-media-minmax')),
                require((0, utils_1.getSharedPkgCompiledPath)('postcss-nesting')),
                require((0, utils_1.getSharedPkgCompiledPath)('autoprefixer'))(applyOptionsChain({
                    flexbox: 'no-2009',
                    overrideBrowserslist: browserslist,
                }, config.tools.autoprefixer)),
                enableCssMinify
                    ? require('cssnano')((0, exports.getCssnanoDefaultOptions)())
                    : false,
            ].filter(Boolean),
        },
        sourceMap: enableSourceMap,
    }, config.tools.postcss || {}, utils);
    if (extraPlugins.length) {
        (0, assert_1.default)('postcssOptions' in mergedConfig);
        (0, assert_1.default)('plugins' in mergedConfig.postcssOptions);
        mergedConfig.postcssOptions.plugins.push(...extraPlugins);
    }
    return mergedConfig;
};
exports.getPostcssConfig = getPostcssConfig;
// If the target is 'node' or 'web-worker' and the modules option of css-loader is enabled,
// we must enable exportOnlyLocals to only exports the modules identifier mappings.
// Otherwise, the compiled CSS code may contain invalid code, such as `new URL`.
// https://github.com/webpack-contrib/css-loader#exportonlylocals
const normalizeCssLoaderOptions = (options, exportOnlyLocals) => {
    if (options.modules && exportOnlyLocals) {
        let { modules } = options;
        if (modules === true) {
            modules = { exportOnlyLocals: true };
        }
        else if (typeof modules === 'string') {
            modules = { mode: modules, exportOnlyLocals: true };
        }
        else {
            // create a new object to avoid modifying the original options
            modules = {
                ...modules,
                exportOnlyLocals: true,
            };
        }
        return {
            ...options,
            modules,
        };
    }
    return options;
};
exports.normalizeCssLoaderOptions = normalizeCssLoaderOptions;
const getCssLoaderOptions = async ({ config, enableSourceMap, importLoaders, isServer, isWebWorker, localIdentName, }) => {
    const { applyOptionsChain } = await Promise.resolve().then(() => __importStar(require('@modern-js/utils')));
    const { cssModules } = config.output;
    const mergedCssLoaderOptions = applyOptionsChain({
        importLoaders,
        modules: {
            auto: (0, exports.getCssModulesAutoRule)(cssModules, config.output.disableCssModuleExtension),
            exportLocalsConvention: 'camelCase',
            localIdentName,
        },
        sourceMap: enableSourceMap,
    }, config.tools.cssLoader, undefined, lodash_1.merge);
    const cssLoaderOptions = (0, exports.normalizeCssLoaderOptions)(mergedCssLoaderOptions, isServer || isWebWorker);
    return cssLoaderOptions;
};
exports.getCssLoaderOptions = getCssLoaderOptions;
const isUseCssExtract = (config, target) => !config.output.disableCssExtract &&
    target !== 'node' &&
    target !== 'web-worker';
exports.isUseCssExtract = isUseCssExtract;
