import esbuild from "esbuild";
import fs from "fs";
import {fileURLToPath} from "url";
import {transform} from "@astrojs/compiler";
import {decode} from "sourcemap-codec";
import {getViteTransform, transformWithVite} from "./styles.js";
function astro({config, devServer}) {
  let viteTransform;
  return {
    name: "@astrojs/vite-plugin-astro",
    enforce: "pre",
    configResolved(resolvedConfig) {
      viteTransform = getViteTransform(resolvedConfig);
    },
    async load(id) {
      if (!id.endsWith(".astro")) {
        return null;
      }
      const isPage = id.startsWith(fileURLToPath(config.pages)) || id.startsWith(fileURLToPath(config.layouts));
      let source = await fs.promises.readFile(id, "utf8");
      let tsResult;
      try {
        tsResult = await transform(source, {
          as: isPage ? "document" : "fragment",
          site: config.buildOptions.site,
          sourcefile: id,
          sourcemap: "both",
          internalURL: "astro/internal",
          preprocessStyle: async (value, attrs) => {
            var _a;
            if (!attrs || !attrs.lang)
              return null;
            const result = await transformWithVite(value, attrs, id, viteTransform);
            if (!result) {
              return result;
            }
            return {code: result.code, map: (_a = result.map) == null ? void 0 : _a.toString()};
          }
        });
        const {code, map} = await esbuild.transform(tsResult.code, {loader: "ts", sourcemap: "external", sourcefile: id});
        return {
          code,
          map
        };
      } catch (err) {
        if (err.errors && (tsResult == null ? void 0 : tsResult.map)) {
          const json = JSON.parse(tsResult.map);
          const mappings = decode(json.mappings);
          const focusMapping = mappings[err.errors[0].location.line + 1];
          err.sourceLoc = {file: id, line: (focusMapping[0][2] || 0) + 1, column: (focusMapping[0][3] || 0) + 1};
        }
        throw err;
      }
    },
    async handleHotUpdate(context) {
      if (devServer) {
        return devServer.handleHotUpdate(context);
      }
    },
    transformIndexHtml() {
      return [
        {
          injectTo: "head-prepend",
          tag: "script",
          attrs: {
            type: "module",
            src: "/@astro/runtime/client/hmr"
          }
        }
      ];
    }
  };
}
export {
  astro as default
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vc3JjL3ZpdGUtcGx1Z2luLWFzdHJvL2luZGV4L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