import { STYLE_EXTENSIONS } from "../core/ssr/css.js";
import * as path from "path";
import esbuild from "esbuild";
const PLUGIN_NAME = "@astrojs/rollup-plugin-build-css";
const ASTRO_STYLE_PREFIX = "@astro-inline-style";
const ASTRO_PAGE_STYLE_PREFIX = "@astro-page-all-styles";
const isCSSRequest = (request) => STYLE_EXTENSIONS.has(path.extname(request));
function getAstroPageStyleId(pathname) {
  let styleId = ASTRO_PAGE_STYLE_PREFIX + pathname;
  if (styleId.endsWith("/")) {
    styleId += "index";
  }
  styleId += ".js";
  return styleId;
}
function getAstroStyleId(pathname) {
  let styleId = ASTRO_STYLE_PREFIX + pathname;
  if (styleId.endsWith("/")) {
    styleId += "index";
  }
  styleId += ".css";
  return styleId;
}
function getAstroStylePathFromId(id) {
  return id.substr(ASTRO_STYLE_PREFIX.length + 1);
}
function isStyleVirtualModule(id) {
  return id.startsWith(ASTRO_STYLE_PREFIX);
}
function isPageStyleVirtualModule(id) {
  return id.startsWith(ASTRO_PAGE_STYLE_PREFIX);
}
function rollupPluginAstroBuildCSS(options) {
  const { astroPageStyleMap, astroStyleMap, chunkToReferenceIdMap, pureCSSChunks } = options;
  const styleSourceMap = new Map();
  return {
    name: PLUGIN_NAME,
    configResolved(resolvedConfig) {
      const plugins = resolvedConfig.plugins;
      const viteCSSPostIndex = resolvedConfig.plugins.findIndex((p) => p.name === "vite:css-post");
      if (viteCSSPostIndex !== -1) {
        const viteCSSPost = plugins[viteCSSPostIndex];
        delete viteCSSPost.renderChunk;
        delete viteCSSPost.generateBundle;
        const ourIndex = plugins.findIndex((p) => p.name === PLUGIN_NAME);
        const ourPlugin = plugins[ourIndex];
        plugins.splice(ourIndex, 1);
        plugins.splice(viteCSSPostIndex - 1, 0, ourPlugin);
      }
    },
    async resolveId(id) {
      if (isPageStyleVirtualModule(id)) {
        return id;
      }
      if (isStyleVirtualModule(id)) {
        return id;
      }
      return void 0;
    },
    async load(id) {
      if (isPageStyleVirtualModule(id)) {
        const source = astroPageStyleMap.get(id);
        return source;
      }
      if (isStyleVirtualModule(id)) {
        return astroStyleMap.get(id);
      }
      return null;
    },
    async transform(value, id) {
      if (isStyleVirtualModule(id)) {
        styleSourceMap.set(id, value);
        return null;
      }
      if (isCSSRequest(id)) {
        styleSourceMap.set(id, value);
      }
      return null;
    },
    async renderChunk(_code, chunk) {
      let chunkCSS = "";
      let isPureCSS = true;
      for (const [id] of Object.entries(chunk.modules)) {
        if (!isCSSRequest(id) && !isPageStyleVirtualModule(id)) {
          isPureCSS = false;
        }
        if (styleSourceMap.has(id)) {
          chunkCSS += styleSourceMap.get(id);
        }
      }
      if (isPureCSS) {
        const { code: minifiedCSS } = await esbuild.transform(chunkCSS, {
          loader: "css",
          minify: true
        });
        const referenceId = this.emitFile({
          name: chunk.name + ".css",
          type: "asset",
          source: minifiedCSS
        });
        pureCSSChunks.add(chunk);
        chunkToReferenceIdMap.set(chunk.fileName, referenceId);
      }
      return null;
    },
    generateBundle(opts, bundle) {
      if (pureCSSChunks.size) {
        const pureChunkFilenames = new Set([...pureCSSChunks].map((chunk) => chunk.fileName));
        const emptyChunkFiles = [...pureChunkFilenames].map((file) => path.basename(file)).join("|").replace(/\./g, "\\.");
        const emptyChunkRE = new RegExp(opts.format === "es" ? `\\bimport\\s*"[^"]*(?:${emptyChunkFiles})";
?` : `\\brequire\\(\\s*"[^"]*(?:${emptyChunkFiles})"\\);
?`, "g");
        for (const [chunkId, chunk] of Object.entries(bundle)) {
          if (chunk.type === "chunk") {
            if (pureCSSChunks.has(chunk)) {
              delete bundle[chunkId];
            } else {
              chunk.code = chunk.code.replace(emptyChunkRE, (m) => `/* empty css ${"".padEnd(m.length - 15)}*/`);
            }
          }
        }
      }
    }
  };
}
export {
  getAstroPageStyleId,
  getAstroStyleId,
  getAstroStylePathFromId,
  rollupPluginAstroBuildCSS
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vc3JjL3ZpdGUtcGx1Z2luL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