import fs from "fs";
import slash from "slash";
import {fileURLToPath} from "url";
import {createRequire} from "module";
import vite from "./vite.js";
import astroVitePlugin from "../vite-plugin-astro/index.js";
import astroPostprocessVitePlugin from "../vite-plugin-astro-postprocess/index.js";
import markdownVitePlugin from "../vite-plugin-markdown/index.js";
import jsxVitePlugin from "../vite-plugin-jsx/index.js";
import fetchVitePlugin from "../vite-plugin-fetch/index.js";
import {getPackageJSON, parseNpmName} from "./util.js";
const require2 = createRequire(import.meta.url);
async function createVite(viteConfig, {astroConfig, logging, devServer}) {
  const optimizedDeps = new Set();
  const dedupe = new Set();
  const plugins = [];
  const packageJSON = await getPackageJSON(astroConfig.projectRoot) || {};
  const userDeps = Object.keys((packageJSON == null ? void 0 : packageJSON.dependencies) || {});
  userDeps.forEach((dep) => {
    optimizedDeps.add(dep);
  });
  const userDevDeps = Object.keys((packageJSON == null ? void 0 : packageJSON.devDependencies) || {});
  const {external, noExternal} = await viteSSRDeps([...userDeps, ...userDevDeps]);
  await Promise.all(astroConfig.renderers.map(async (name) => {
    const {default: renderer} = await import(name);
    if (renderer.client) {
      optimizedDeps.add(name + renderer.client.substr(1));
    }
    for (let dep of [...renderer.knownEntrypoints || [], ...renderer.polyfills || []]) {
      if (dep[0] === ".")
        dep = name + dep.substr(1);
      optimizedDeps.add(dep);
      dedupe.add(dep);
    }
    if (renderer.vitePlugins) {
      plugins.push(...renderer.vitePlugins);
    }
    if (renderer.external) {
      for (const dep of renderer.external) {
        external.add(dep);
        noExternal.delete(dep);
      }
    }
  }));
  fs.readdirSync(new URL("../runtime/client", import.meta.url)).forEach((hydrator) => {
    optimizedDeps.add(`astro/client/${hydrator}`);
  });
  return vite.mergeConfig({
    cacheDir: fileURLToPath(new URL("./node_modules/.vite/", astroConfig.projectRoot)),
    clearScreen: false,
    logLevel: "error",
    optimizeDeps: {
      entries: ["src/**/*"],
      include: [...optimizedDeps]
    },
    plugins: [
      astroVitePlugin({config: astroConfig, devServer}),
      markdownVitePlugin({config: astroConfig, devServer}),
      jsxVitePlugin({config: astroConfig, logging}),
      astroPostprocessVitePlugin({config: astroConfig, devServer}),
      fetchVitePlugin(),
      ...plugins
    ],
    publicDir: fileURLToPath(astroConfig.public),
    resolve: {
      dedupe: [...dedupe]
    },
    root: fileURLToPath(astroConfig.projectRoot),
    server: {
      fs: {strict: true},
      hmr: process.env.NODE_ENV === "test" || process.env.NODE_ENV === "production" ? false : void 0,
      proxy: {}
    },
    ssr: {
      external: [...external],
      noExternal: [...noExternal]
    }
  }, vite.mergeConfig(viteConfig, astroConfig.vite || {}));
}
async function viteSSRDeps(deps) {
  const skip = new Set();
  const external = new Set();
  const noExternal = new Set();
  async function sortPkg(spec) {
    if (external.has(spec) || noExternal.has(spec) || skip.has(spec))
      return;
    const pkg = parseNpmName(spec);
    if (!pkg) {
      skip.add(spec);
      return;
    }
    try {
      const moduleLoc = require2.resolve(spec);
      if (!moduleLoc) {
        skip.add(spec);
        return;
      }
      let cwd = new URL("../", `file://${slash(moduleLoc)}/`);
      let packageJSON = await getPackageJSON(cwd);
      while (!packageJSON) {
        const next = new URL("../", cwd);
        if (next.href === cwd.href)
          return;
        cwd = next;
        packageJSON = await getPackageJSON(cwd);
      }
      if (!packageJSON) {
        skip.add(spec);
        return;
      }
      let isExternal = true;
      if (packageJSON.type === "module")
        isExternal = false;
      if (pkg.name === "@sveltejs/vite-plugin-svelte")
        isExternal = true;
      if (pkg.name === "micromark-util-events-to-acorn")
        isExternal = true;
      if (pkg.name === "unified")
        isExternal = true;
      if (isExternal === true) {
        external.add(spec);
      } else {
        noExternal.add(spec);
      }
      await Promise.all(Object.keys(packageJSON.dependencies || {}).map(sortPkg));
    } catch (err) {
      skip.add(spec);
      return;
    }
  }
  await Promise.all(deps.map(sortPkg));
  const externalSorted = [...external];
  externalSorted.sort((a, b) => a.localeCompare(b, "en-us", {numeric: true}));
  const noExternalSorted = [...noExternal];
  noExternalSorted.sort((a, b) => a.localeCompare(b, "en-us", {numeric: true}));
  return {
    external: new Set([...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