"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
function _path() {
  const data = _interopRequireDefault(require("path"));
  _path = function () {
    return data;
  };
  return data;
}
function _sourceMap() {
  const data = _interopRequireDefault(require("@parcel/source-map"));
  _sourceMap = function () {
    return data;
  };
  return data;
}
function _plugin() {
  const data = require("@parcel/plugin");
  _plugin = function () {
    return data;
  };
  return data;
}
function _utils() {
  const data = require("@parcel/utils");
  _utils = function () {
    return data;
  };
  return data;
}
function native() {
  const data = _interopRequireWildcard(require("lightningcss"));
  native = function () {
    return data;
  };
  return data;
}
function _browserslist() {
  const data = _interopRequireDefault(require("browserslist"));
  _browserslist = function () {
    return data;
  };
  return data;
}
function _nullthrows() {
  const data = _interopRequireDefault(require("nullthrows"));
  _nullthrows = function () {
    return data;
  };
  return data;
}
function _diagnostic() {
  const data = _interopRequireWildcard(require("@parcel/diagnostic"));
  _diagnostic = function () {
    return data;
  };
  return data;
}
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; }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const {
  transform,
  transformStyleAttribute,
  browserslistToTargets
} = native();
var _default = exports.default = new (_plugin().Transformer)({
  async loadConfig({
    config,
    options
  }) {
    var _contents$cssModules, _contents$cssModules2, _contents$cssModules3, _contents$cssModules4;
    let conf = await config.getConfigFrom(options.projectRoot + '/index', [], {
      packageKey: '@parcel/transformer-css'
    });
    let contents = conf === null || conf === void 0 ? void 0 : conf.contents;
    if (typeof (contents === null || contents === void 0 || (_contents$cssModules = contents.cssModules) === null || _contents$cssModules === void 0 ? void 0 : _contents$cssModules.include) === 'string') {
      contents.cssModules.include = [(0, _utils().globToRegex)(contents.cssModules.include)];
    } else if (Array.isArray(contents === null || contents === void 0 || (_contents$cssModules2 = contents.cssModules) === null || _contents$cssModules2 === void 0 ? void 0 : _contents$cssModules2.include)) {
      contents.cssModules.include = contents.cssModules.include.map(include => typeof include === 'string' ? (0, _utils().globToRegex)(include) : include);
    }
    if (typeof (contents === null || contents === void 0 || (_contents$cssModules3 = contents.cssModules) === null || _contents$cssModules3 === void 0 ? void 0 : _contents$cssModules3.exclude) === 'string') {
      contents.cssModules.exclude = [(0, _utils().globToRegex)(contents.cssModules.exclude)];
    } else if (Array.isArray(contents === null || contents === void 0 || (_contents$cssModules4 = contents.cssModules) === null || _contents$cssModules4 === void 0 ? void 0 : _contents$cssModules4.exclude)) {
      contents.cssModules.exclude = contents.cssModules.exclude.map(exclude => typeof exclude === 'string' ? (0, _utils().globToRegex)(exclude) : exclude);
    }
    return contents;
  },
  async transform({
    asset,
    config,
    options,
    logger
  }) {
    // Normalize the asset's environment so that properties that only affect JS don't cause CSS to be duplicated.
    // For example, with ESModule and CommonJS targets, only a single shared CSS bundle should be produced.
    let env = {
      context: asset.env.context,
      outputFormat: asset.env.outputFormat,
      engines: asset.env.engines,
      includeNodeModules: asset.env.includeNodeModules,
      sourceType: asset.env.sourceType,
      isLibrary: asset.env.isLibrary,
      shouldOptimize: asset.env.shouldOptimize,
      shouldScopeHoist: asset.env.shouldScopeHoist,
      sourceMap: asset.env.sourceMap,
      loc: asset.env.loc
    };
    asset.setEnvironment({
      context: asset.env.context === 'react-server' || asset.env.context === 'react-client' ? 'react-client' : 'browser',
      engines: {
        browsers: asset.env.engines.browsers
      },
      shouldOptimize: asset.env.shouldOptimize,
      shouldScopeHoist: asset.env.shouldScopeHoist,
      sourceMap: asset.env.sourceMap
    });
    let [code, originalMap] = await Promise.all([asset.getBuffer(), asset.getMap(),
    // $FlowFixMe native.default is the init function only when bundled for the browser build
    process.browser && native().default()]);
    let targets = getTargets(asset.env.engines.browsers);
    let res;
    try {
      if (asset.meta.type === 'attr') {
        res = transformStyleAttribute({
          code,
          analyzeDependencies: true,
          errorRecovery: (config === null || config === void 0 ? void 0 : config.errorRecovery) || false,
          targets
        });
      } else {
        let cssModules = false;
        if (asset.meta.type !== 'tag' && asset.meta.cssModulesCompiled == null) {
          let cssModulesConfig = config === null || config === void 0 ? void 0 : config.cssModules;
          let isCSSModule = /\.module\./.test(asset.filePath);
          if (asset.isSource) {
            var _cssModulesConfig$exc;
            let projectRootPath = _path().default.relative(options.projectRoot, asset.filePath);
            if (typeof cssModulesConfig === 'boolean') {
              isCSSModule = true;
            } else if (cssModulesConfig !== null && cssModulesConfig !== void 0 && cssModulesConfig.include) {
              isCSSModule = cssModulesConfig.include.some(include => include.test(projectRootPath));
            } else if (cssModulesConfig !== null && cssModulesConfig !== void 0 && cssModulesConfig.global) {
              isCSSModule = true;
            }
            if (cssModulesConfig !== null && cssModulesConfig !== void 0 && (_cssModulesConfig$exc = cssModulesConfig.exclude) !== null && _cssModulesConfig$exc !== void 0 && _cssModulesConfig$exc.some(exclude => exclude.test(projectRootPath))) {
              isCSSModule = false;
            }
          }
          if (isCSSModule) {
            if (cssModulesConfig !== null && cssModulesConfig !== void 0 && cssModulesConfig.dashedIdents && !asset.isSource) {
              cssModulesConfig.dashedIdents = false;
            }
            cssModules = cssModulesConfig ?? true;
          }
        }
        res = transform({
          filename: (0, _utils().normalizeSeparators)(_path().default.relative(options.projectRoot, asset.filePath)),
          code,
          cssModules,
          analyzeDependencies: asset.meta.hasDependencies !== false ? {
            preserveImports: true
          } : false,
          sourceMap: !!asset.env.sourceMap,
          drafts: config === null || config === void 0 ? void 0 : config.drafts,
          pseudoClasses: config === null || config === void 0 ? void 0 : config.pseudoClasses,
          errorRecovery: (config === null || config === void 0 ? void 0 : config.errorRecovery) || false,
          targets
        });
      }
    } catch (err) {
      var _err$data;
      err.filePath = asset.filePath;
      let diagnostic = (0, _diagnostic().errorToDiagnostic)(err, {
        origin: '@parcel/transformer-css'
      });
      if (((_err$data = err.data) === null || _err$data === void 0 ? void 0 : _err$data.type) === 'AmbiguousUrlInCustomProperty' && err.data.url) {
        let p = '/' + (0, _utils().relativePath)(options.projectRoot, _path().default.resolve(_path().default.dirname(asset.filePath), err.data.url), false);
        diagnostic[0].hints = [`Replace with: url(${p})`];
        diagnostic[0].documentationURL = 'https://parceljs.org/languages/css/#url()';
      }
      throw new (_diagnostic().default)({
        diagnostic
      });
    }
    if (res.warnings) {
      for (let warning of res.warnings) {
        logger.warn({
          message: warning.message,
          codeFrames: [{
            filePath: asset.filePath,
            codeHighlights: [{
              start: {
                line: warning.loc.line,
                column: warning.loc.column + 1
              },
              end: {
                line: warning.loc.line,
                column: warning.loc.column + 1
              }
            }]
          }]
        });
      }
    }
    if (res.map != null) {
      let vlqMap = JSON.parse(Buffer.from(res.map).toString());
      let map = new (_sourceMap().default)(options.projectRoot);
      map.addVLQMap(vlqMap);
      if (originalMap) {
        map.extends(originalMap);
      }
      asset.setMap(map);
    }
    if (res.dependencies) {
      for (let dep of res.dependencies) {
        let loc = convertLoc(dep.loc);
        if (originalMap) {
          loc = (0, _utils().remapSourceLocation)(loc, originalMap);
        }
        if (dep.type === 'import' && !res.exports) {
          asset.addDependency({
            specifier: dep.url,
            specifierType: 'url',
            loc,
            packageConditions: ['style'],
            meta: {
              // For the glob resolver to distinguish between `@import` and other URL dependencies.
              isCSSImport: true,
              media: dep.media,
              placeholder: dep.placeholder
            }
          });
        } else if (dep.type === 'url') {
          asset.addURLDependency(dep.url, {
            loc,
            meta: {
              placeholder: dep.placeholder
            }
          });
        }
      }
    }
    let assets = [asset];
    let buffer = Buffer.from(res.code);
    if (res.exports != null) {
      let exports = res.exports;
      asset.symbols.ensure();
      asset.symbols.set('default', 'default');
      let dependencies = new Map();
      let locals = new Map();
      let c = 0;
      let depjs = '';
      let js = '';
      let cssImports = '';
      for (let key in exports) {
        locals.set(exports[key].name, key);
      }
      asset.uniqueKey ??= asset.id;
      let seen = new Set();
      let add = key => {
        if (seen.has(key)) {
          return;
        }
        seen.add(key);
        let e = exports[key];
        let s = `module.exports[${JSON.stringify(key)}] = \`${e.name}`;
        for (let ref of e.composes) {
          s += ' ';
          if (ref.type === 'local') {
            let exported = (0, _nullthrows().default)(locals.get(ref.name));
            add(exported);
            s += '${' + `module.exports[${JSON.stringify(exported)}]` + '}';
            asset.addDependency({
              specifier: (0, _nullthrows().default)(asset.uniqueKey),
              specifierType: 'esm',
              symbols: new Map([[exported, {
                local: ref.name,
                isWeak: false,
                loc: null
              }]]),
              env
            });
          } else if (ref.type === 'global') {
            s += ref.name;
          } else if (ref.type === 'dependency') {
            let d = dependencies.get(ref.specifier);
            if (d == null) {
              d = `dep_${c++}`;
              depjs += `import * as ${d} from ${JSON.stringify(ref.specifier)};\n`;
              dependencies.set(ref.specifier, d);
              cssImports += `@import "${ref.specifier}";\n`;
              asset.addDependency({
                specifier: ref.specifier,
                specifierType: 'esm',
                packageConditions: ['style'],
                env
              });
            }
            s += '${' + `${d}[${JSON.stringify(ref.name)}]` + '}';
          }
        }
        s += '`;\n';

        // If the export is referenced internally (e.g. used @keyframes), add a self-reference
        // to the JS so the symbol is retained during tree-shaking.
        if (e.isReferenced) {
          s += `module.exports[${JSON.stringify(key)}];\n`;
          asset.addDependency({
            specifier: (0, _nullthrows().default)(asset.uniqueKey),
            specifierType: 'esm',
            symbols: new Map([[key, {
              local: exports[key].name,
              isWeak: false,
              loc: null
            }]]),
            env
          });
        }
        js += s;
      };

      // It's possible that the exports can be ordered differently between builds.
      // Sorting by key is safe as the order is irrelevant but needs to be deterministic.
      for (let key of Object.keys(exports).sort()) {
        asset.symbols.set(key, exports[key].name);
        add(key);
      }
      if (res.dependencies) {
        for (let dep of res.dependencies) {
          if (dep.type === 'import') {
            // TODO: Figure out how to treeshake this
            let d = `dep_$${c++}`;
            depjs += `import * as ${d} from ${JSON.stringify(dep.url)};\n`;
            js += `for (let key in ${d}) { if (key in module.exports) module.exports[key] += ' ' + ${d}[key]; else module.exports[key] = ${d}[key]; }\n`;
            asset.symbols.set('*', '*');
          }
        }
      }
      if (res.references != null) {
        let references = res.references;
        for (let symbol in references) {
          let reference = references[symbol];
          asset.addDependency({
            specifier: reference.specifier,
            specifierType: 'esm',
            packageConditions: ['style'],
            symbols: new Map([[reference.name, {
              local: symbol,
              isWeak: false,
              loc: null
            }]]),
            env
          });
          asset.meta.hasReferences = true;
          cssImports += `@import "${reference.specifier}";\n`;
        }
      }
      assets.push({
        type: 'js',
        content: depjs + js,
        dependencies: [],
        env
      });

      // Prepend @import rules for each composes dependency so packager knows where to insert them.
      if (cssImports.length > 0) {
        buffer = Buffer.concat([Buffer.from(cssImports), buffer]);
      }
    }
    asset.setBuffer(buffer);
    return assets;
  }
});
let cache = new Map();
function getTargets(browsers) {
  if (browsers == null) {
    return undefined;
  }
  let cached = cache.get(browsers);
  if (cached != null) {
    return cached;
  }
  let targets = browserslistToTargets((0, _browserslist().default)(browsers));
  cache.set(browsers, targets);
  return targets;
}
function convertLoc(loc) {
  return {
    filePath: loc.filePath,
    start: {
      line: loc.start.line,
      column: loc.start.column
    },
    end: {
      line: loc.end.line,
      column: loc.end.column + 1
    }
  };
}