import { createRequire } from 'module'; const require = createRequire(import.meta.url);

// packages/dev-tools/vite/main.ts
import { createDevTools } from "../core/index.mjs";
import { createDevToolsNodeSys } from "../node/index.mjs";
import { createDevToolsServer } from "../server/index.mjs";

// packages/dev-tools/common/dotenv.ts
async function parseDotEnvFile(sys, envPath) {
  const envContent = await sys.readFile(envPath);
  if (typeof envContent === "string") {
    return parseDotEnvContent(envContent);
  }
  return null;
}
function parseDotEnvContent(envContent) {
  const envVars = {};
  const lines = envContent.replace(/\r\n?/gm, "\n");
  let match;
  while ((match = DOTENV_LINE.exec(lines)) != null) {
    const key = match[1];
    let value = match[2] || "";
    value = value.trim();
    const maybeQuote = value[0];
    value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
    if (maybeQuote === '"') {
      value = value.replace(/\\n/g, "\n");
      value = value.replace(/\\r/g, "\r");
    }
    envVars[key] = value;
  }
  return envVars;
}
var DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;

// packages/dev-tools/vite/main.ts
import path from "node:path";

// packages/dev-tools/common/constants.ts
var DEV_TOOLS_CLIENT_SCRIPT_PATH = "/~builder-dev-tools.js";

// packages/dev-tools/vite/main.ts
function builderDevTools(opts = {}) {
  const plugin = {
    name: "vite-plugin-builder-dev-tools",
    async configureServer(viteDevServer) {
      if (process.argv.includes("codegen")) {
        return;
      }
      const sys = await createDevToolsNodeSys({
        cwd: path.normalize(viteDevServer.config.root)
      });
      const devTools = await createDevTools(sys);
      const devToolsServer = await createDevToolsServer({
        ...devTools,
        getClientId: () => "vite-builder-dev-tools",
        closeAppServer: async () => {
          sys.debug("close server");
          await viteDevServer?.close();
        },
        restartAppServer: async () => {
          sys.debug("restart server");
          await viteDevServer?.restart();
        },
        enableAppWatch: async (enable) => {
          if (enable) {
            sys.debug("enable watch");
            viteDevServer?.watcher.add(viteDevServer.config.root);
            const gitPath = sys.join(viteDevServer.config.root, ".git");
            const nodeModulesPath = sys.join(
              viteDevServer.config.root,
              "node_modules"
            );
            viteDevServer?.watcher.unwatch([gitPath, nodeModulesPath]);
          } else {
            sys.debug("disable watch");
            viteDevServer?.watcher.unwatch(viteDevServer.config.root);
          }
          return enable;
        },
        ...sys,
        ...opts
      });
      viteDevServer.watcher.on("change", async (filePath) => {
        if (filePath.includes(".env")) {
          const envVars = await parseDotEnvFile(sys, filePath);
          if (envVars) {
            const envKeys = Object.keys(envVars);
            envKeys.forEach((key) => {
              process.env[key] = envVars[key];
            });
          }
        }
      });
      viteDevServer.middlewares.use(async (_req, res, next) => {
        try {
          const orgResponseEnd = res.end;
          res.end = function(...args) {
            const contentType = (res.getHeader("Content-Type") || "").toString();
            if (contentType.includes("text/html")) {
              const url = new URL(
                DEV_TOOLS_CLIENT_SCRIPT_PATH,
                devToolsServer.getUrl()
              );
              res.write(`<script defer src="${url}"></script>`);
            }
            return orgResponseEnd.apply(this, args);
          };
          next();
        } catch (e) {
          next(e);
        }
      });
    }
  };
  return plugin;
}
export {
  builderDevTools
};
