import esbuild from "esbuild";
import { fileURLToPath } from "url";
import { getViteTransform } from "./styles.js";
import { parseAstroRequest } from "./query.js";
import { cachedCompilation, invalidateCompilation } from "./compile.js";
import ancestor from "common-ancestor-path";
const FRONTMATTER_PARSE_REGEXP = /^\-\-\-(.*)^\-\-\-/ms;
function astro({ config, logging }) {
  let viteTransform;
  return {
    name: "@astrojs/vite-plugin-astro",
    enforce: "pre",
    configResolved(resolvedConfig) {
      viteTransform = getViteTransform(resolvedConfig);
    },
    async resolveId(id) {
      if (parseAstroRequest(id).query.astro) {
        return id;
      }
    },
    async load(id, opts) {
      let { filename, query } = parseAstroRequest(id);
      if (query.astro) {
        if (query.type === "style") {
          if (filename.startsWith("/@fs")) {
            filename = filename.slice("/@fs".length);
          } else if (filename.startsWith("/") && !ancestor(filename, config.projectRoot.pathname)) {
            filename = new URL("." + filename, config.projectRoot).pathname;
          }
          const transformResult = await cachedCompilation(config, filename, null, viteTransform, opts);
          if (typeof query.index === "undefined") {
            throw new Error(`Requests for Astro CSS must include an index.`);
          }
          const csses = transformResult.css;
          const code = csses[query.index];
          return {
            code
          };
        }
      }
      return null;
    },
    async transform(source, id, opts) {
      if (!id.endsWith(".astro")) {
        return;
      }
      try {
        const transformResult = await cachedCompilation(config, id, source, viteTransform, opts);
        const { code, map } = await esbuild.transform(transformResult.code, {
          loader: "ts",
          sourcemap: "external",
          sourcefile: id
        });
        return {
          code,
          map
        };
      } catch (err) {
        const scannedFrontmatter = FRONTMATTER_PARSE_REGEXP.exec(source);
        if (scannedFrontmatter) {
          try {
            await esbuild.transform(scannedFrontmatter[1], { loader: "ts", sourcemap: false, sourcefile: id });
          } catch (frontmatterErr) {
            if (frontmatterErr && frontmatterErr.message) {
              frontmatterErr.message = frontmatterErr.message.replace("end of file", "end of frontmatter");
            }
            throw frontmatterErr;
          }
        }
        if (err.stack.includes("wasm-function")) {
          const search = new URLSearchParams({
            labels: "compiler",
            title: "\u{1F41B} BUG: `@astrojs/compiler` panic",
            body: `### Describe the Bug
    
    \`@astrojs/compiler\` encountered an unrecoverable error when compiling the following file.
    
    **${id.replace(fileURLToPath(config.projectRoot), "")}**
    \`\`\`astro
    ${source}
    \`\`\`
    `
          });
          err.url = `https://github.com/withastro/astro/issues/new?${search.toString()}`;
          err.message = `Error: Uh oh, the Astro compiler encountered an unrecoverable error!
    
    Please open
    a GitHub issue using the link below:
    ${err.url}`;
          if (logging.level !== "debug") {
            err.stack = `    at ${id}`;
          }
        }
        throw err;
      }
    },
    async handleHotUpdate(context) {
      invalidateCompilation(config, context.file);
    }
  };
}
export {
  astro as default
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vc3JjL3ZpdGUtcGx1Z2luLWFzdHJvL2luZGV4LnRzIl0sCiAgIm1hcHBpbmdzIjogIkFBSUE7QUFDQTtBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBRUEsTUFBTSwyQkFBMkI7QUFRbEIsZUFBZSxFQUFFLFFBQVEsV0FBNEM7QUFDbkYsTUFBSTtBQUNKLFNBQU87QUFBQSxJQUNOLE1BQU07QUFBQSxJQUNOLFNBQVM7QUFBQSxJQUNULGVBQWUsZ0JBQWdCO0FBQzlCLHNCQUFnQixpQkFBaUI7QUFBQTtBQUFBLFVBRzVCLFVBQVUsSUFBSTtBQUVuQixVQUFJLGtCQUFrQixJQUFJLE1BQU0sT0FBTztBQUN0QyxlQUFPO0FBQUE7QUFBQTtBQUFBLFVBR0gsS0FBSyxJQUFJLE1BQU07QUFDcEIsVUFBSSxFQUFFLFVBQVUsVUFBVSxrQkFBa0I7QUFDNUMsVUFBSSxNQUFNLE9BQU87QUFDaEIsWUFBSSxNQUFNLFNBQVMsU0FBUztBQUMzQixjQUFJLFNBQVMsV0FBVyxTQUFTO0FBQ2hDLHVCQUFXLFNBQVMsTUFBTSxPQUFPO0FBQUEscUJBQ3ZCLFNBQVMsV0FBVyxRQUFRLENBQUMsU0FBUyxVQUFVLE9B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