import { dirname as __pathDirname } from 'path';
import { fileURLToPath as __fileURLToPath } from 'url';
var __dirname = (function() {
  try {
    var url = import.meta?.url;
    if (url) return __pathDirname(__fileURLToPath(url));
  } catch (e) {}
  try {
    if (typeof __filename !== 'undefined') return __pathDirname(__filename);
  } catch (e) {}
  return process.cwd();
})();
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});

// src/integrations/next.ts
import fs6 from "fs";
import path9 from "path";

// src/codegen/config-injector.ts
function generateConfigInjectionCode(config) {
  if (!config.clientUrl && !config.rootSelector && !config.theme && !config.assets && !config.launchEditor) {
    return "";
  }
  const configParts = [];
  if (config.clientUrl) {
    configParts.push(`window.__REACT_DEVTOOLS_CONFIG__.clientUrl = ${JSON.stringify(config.clientUrl)};`);
  }
  if (config.rootSelector) {
    configParts.push(`window.__REACT_DEVTOOLS_CONFIG__.rootSelector = ${JSON.stringify(config.rootSelector)};`);
  }
  if (config.theme) {
    configParts.push(`window.__REACT_DEVTOOLS_CONFIG__.theme = ${JSON.stringify(config.theme)};`);
  }
  if (config.assets) {
    configParts.push(`window.__REACT_DEVTOOLS_CONFIG__.assets = ${JSON.stringify(config.assets)};`);
  }
  if (config.launchEditor) {
    configParts.push(`window.__REACT_DEVTOOLS_CONFIG__.launchEditor = ${JSON.stringify(config.launchEditor)};`);
  }
  return `
if (typeof window !== 'undefined') {
  window.__REACT_DEVTOOLS_CONFIG__ = window.__REACT_DEVTOOLS_CONFIG__ || {};
  ${configParts.join("\n  ")}
}
`.trim();
}

// src/codegen/css-injector.ts
import fs from "fs";
import path from "path";
function readAndEscapeCSSContent(cssPath) {
  if (!fs.existsSync(cssPath)) {
    return "";
  }
  return fs.readFileSync(cssPath, "utf-8").replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
}
function generateGlobalsWithCSSCode(overlayDir) {
  const cssPath = path.join(overlayDir, "react-devtools-overlay.css");
  const cssContent = readAndEscapeCSSContent(cssPath);
  let code = `
// React DevTools: Setup React globals and CSS for overlay
// SUpport both npm-installed React and CDN-loaded React (like singleSpa)

if (typeof window !== 'undefined') {
  // Check if React is already available on window (CDN scenario)
  var React = window.React;
  var ReactDOM = window.ReactDOM;

  // if not found, try to require from node_modules
  if (!React) {
    try {
      React = require('react');
      window.React = React;
    } catch (e) {
      // React not available via require, must be loaded via CDN
    }
  }

  if (!ReactDOM) {
    try {
      ReactDOM = require('react-dom');
      window.ReactDOM = ReactDOM;
    } catch (e) {
      // ReactDOM not available via require, must be loaded via CDN
    }
  }

  // Try to add createRoot support for React 18+ (optional)
  if (ReactDOM && !ReactDOM.createRoot) {
    try {
      var ReactDOMClient = require('react-dom/client');
      if (ReactDOMClient && ReactDOMClient.createRoot) {
        window.ReactDOM = Object.assign({}, ReactDOM, ReactDOMClient);
      }
    } catch (e) {
      // react-dom/client not available, which is fine for React 17 or CDN
    }
  }
`;
  if (cssContent) {
    code += `
  // Inject CSS styles for React DevTools overlay
  if (!document.querySelector('style[data-react-devtools]')) {
    var style = document.createElement('style');
    style.setAttribute('data-react-devtools', 'true');
    style.textContent = \`${cssContent}\`;
    document.head.appendChild(style);
  }
`;
  }
  code += `}
`;
  return code.trim();
}

// src/codegen/scan-init.ts
import path2 from "path";

// src/config/normalize.ts
import path3 from "path";
function shouldEnableDevTools(enabledEnvironments, mode, command) {
  if (process.env.VITE_REACT_DEVTOOLS_ENABLED !== void 0) {
    return process.env.VITE_REACT_DEVTOOLS_ENABLED === "true";
  }
  if (enabledEnvironments === true) {
    return command === "serve";
  }
  if (enabledEnvironments === false) {
    return false;
  }
  if (Array.isArray(enabledEnvironments)) {
    const nodeEnv = process.env.NODE_ENV || mode;
    return enabledEnvironments.includes(nodeEnv) || enabledEnvironments.includes(mode);
  }
  return command === "serve";
}
function shouldInjectSource(injectSourceOption, mode, command) {
  if (injectSourceOption !== void 0) {
    return injectSourceOption;
  }
  const nodeEnv = process.env.NODE_ENV || mode;
  const isProduction = nodeEnv === "production" || command === "build" && mode === "production";
  return !isProduction;
}
function normalizeScanConfig(scan, command) {
  var _a, _b;
  if (!scan) {
    return void 0;
  }
  if (scan === true) {
    return {
      enabled: command === "serve",
      // Only enable in dev mode by default
      showToolbar: true
    };
  }
  return __spreadValues({
    enabled: (_a = scan.enabled) != null ? _a : command === "serve",
    showToolbar: (_b = scan.showToolbar) != null ? _b : true
  }, scan);
}
function resolvePluginConfig(options, projectRoot, mode, command) {
  const enabledEnvironments = options.enabledEnvironments;
  const injectSourceOption = options.injectSource;
  const sourcePathMode = options.sourcePathMode || "absolute";
  const isEnabled = shouldEnableDevTools(enabledEnvironments, mode, command);
  const injectSource = shouldInjectSource(injectSourceOption, mode, command);
  const scan = normalizeScanConfig(options.scan, command);
  const plugins = (options.plugins || []).map((plugin) => {
    if (plugin.view && plugin.view.src) {
      let src = plugin.view.src;
      if (!path3.isAbsolute(src)) {
        src = path3.resolve(projectRoot, src);
      }
      return __spreadProps(__spreadValues({}, plugin), {
        view: __spreadProps(__spreadValues({}, plugin.view), {
          src
          // Resolved absolute path
        })
      });
    }
    return plugin;
  });
  return {
    plugins,
    appendTo: options.appendTo,
    enabledEnvironments: enabledEnvironments != null ? enabledEnvironments : true,
    injectSource,
    sourcePathMode,
    projectRoot,
    mode,
    command,
    isEnabled,
    scan,
    clientUrl: options.clientUrl,
    rootSelector: options.rootSelector,
    theme: options.theme,
    assets: options.assets,
    launchEditor: options.launchEditor
  };
}

// src/dir.ts
import { resolve } from "path";
var DIR_DIST = __dirname;
var DIR_OVERLAY = resolve(DIR_DIST, "../src/overlay");

// src/middleware/assets.ts
import fsp from "fs/promises";
import path4 from "path";
function guessType(filePath) {
  if (/\.(?:png|jpe?g|jxl|gif|svg|webp|avif|ico|bmp|tiff?)$/i.test(filePath))
    return "image";
  if (/\.(?:json[5c]?|te?xt|[mc]?[jt]sx?|md[cx]?|markdown|ya?ml|toml)$/i.test(filePath))
    return "text";
  if (/\.(?:mp4|webm|ogv|mov|avi|flv|wmv|mpg|mpeg|mkv|3gp|3g2|mts|m2ts|vob|ogm|ogx|rm|rmvb|asf|amv|divx|m4v|svi|viv|f4v|f4p|f4a|f4b)$/i.test(filePath))
    return "video";
  if (/\.(?:mp3|wav|ogg|flac|aac|wma|alac|ape|ac3|dts|tta|opus|amr|aiff|au|mid|midi|ra|rm|wv|weba|dss|spx|vox|tak|dsf|dff|dsd|cda)$/i.test(filePath))
    return "audio";
  if (/\.(?:woff2?|eot|ttf|otf|ttc|pfa|pfb|pfm|afm)$/i.test(filePath))
    return "font";
  if (/\.wasm$/i.test(filePath))
    return "wasm";
  return "other";
}
var FILE_PATTERNS = [
  // image
  "**/*.{png,jpg,jpeg,gif,svg,webp,avif,ico,bmp,tiff}",
  // video
  "**/*.{mp4,webm,ogv,mov,avi,flv,wmv,mpg,mpeg,mkv,3gp,3g2,m2ts,vob,ogm,ogx,rm,rmvb,asf,amv,divx,m4v,svi,viv,f4v,f4p,f4a,f4b}",
  // audio
  "**/*.{mp3,wav,ogg,flac,aac,wma,alac,ape,ac3,dts,tta,opus,amr,aiff,au,mid,midi,ra,rm,wv,weba,dss,spx,vox,tak,dsf,dff,dsd,cda}",
  // font
  "**/*.{woff,woff2,eot,ttf,otf,ttc,pfa,pfb,pfm,afm}",
  // text
  "**/*.{json,json5,jsonc,txt,text,tsx,jsx,ts,js,md,mdx,mdc,markdown,yaml,yml,toml}",
  // wasm
  "**/*.wasm"
];
var IGNORE_DIRS = [
  "**/node_modules/**",
  "**/dist/**",
  "**/build/**",
  "**/.git/**",
  "**/package-lock.*",
  "**/pnpm-lock.*",
  "**/yarn.lock",
  "**/pnpm-workspace.*"
];
var AssetsScanner = class {
  constructor(config) {
    this.cache = null;
    this.imageMetaCache = /* @__PURE__ */ new Map();
    this.config = {
      root: config.root,
      publicDir: config.publicDir || "public",
      baseUrl: config.baseUrl || "/"
    };
  }
  async scan() {
    const { root, publicDir, baseUrl } = this.config;
    try {
      const fg = await import("fast-glob").then((m) => m.default || m);
      const resolvedPublicDir = path4.isAbsolute(publicDir) ? publicDir : path4.resolve(root, publicDir);
      const relativePublicDir = path4.relative(root, resolvedPublicDir);
      const files = await fg(FILE_PATTERNS, {
        cwd: root,
        onlyFiles: true,
        caseSensitiveMatch: false,
        ignore: IGNORE_DIRS
      });
      this.cache = await Promise.all(files.map(async (relativePath) => {
        const filePath = path4.resolve(root, relativePath);
        const stat = await fsp.lstat(filePath);
        const assetPath = relativePath.replace(new RegExp(`^${relativePublicDir}/`), "");
        return {
          path: assetPath,
          relativePath,
          publicPath: path4.posix.join(baseUrl, assetPath),
          filePath,
          type: guessType(relativePath),
          size: stat.size,
          mtime: stat.mtimeMs
        };
      }));
      return this.cache;
    } catch (error) {
      console.error("[React DevTools] Failed to scan assets:", error);
      return [];
    }
  }
  async getAssets() {
    if (this.cache)
      return this.cache;
    return this.scan();
  }
  clearCache() {
    this.cache = null;
  }
  async getImageMeta(filepath) {
    if (this.imageMetaCache.has(filepath))
      return this.imageMetaCache.get(filepath);
    try {
      const { imageMeta } = await import("image-meta");
      const buffer = await fsp.readFile(filepath);
      const meta = imageMeta(buffer);
      this.imageMetaCache.set(filepath, meta);
      return meta;
    } catch (e) {
      this.imageMetaCache.set(filepath, void 0);
      return void 0;
    }
  }
  async getTextContent(filepath, limit = 500) {
    try {
      const content = await fsp.readFile(filepath, "utf-8");
      return content.slice(0, limit);
    } catch (e) {
      return void 0;
    }
  }
};
var globalScanner = null;
function createAssetsScanner(config) {
  globalScanner = new AssetsScanner(config);
  return globalScanner;
}
function createAssetsMiddleware(config) {
  const scanner = createAssetsScanner(config);
  return async (req, res, next) => {
    const rawUrl = req.url || "";
    const url = new URL(rawUrl, "http://localhost");
    if (url.pathname === "/__react_devtools__/api/assets") {
      try {
        const assets = await scanner.getAssets();
        res.setHeader("Content-Type", "application/json");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.end(JSON.stringify(assets));
        return;
      } catch (e) {
        res.statusCode = 500;
        res.end(JSON.stringify({ error: "Failed to scan assets" }));
        return;
      }
    }
    if (url.pathname === "/__react_devtools__/api/assets/refresh") {
      try {
        scanner.clearCache();
        const assets = await scanner.scan();
        res.setHeader("Content-Type", "application/json");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.end(JSON.stringify(assets));
        return;
      } catch (e) {
        res.statusCode = 500;
        res.end(JSON.stringify({ error: "Failed to refresh assets" }));
        return;
      }
    }
    if (url.pathname === "/__react_devtools__/api/assets/image-meta") {
      const filepath = url.searchParams.get("path");
      if (!filepath) {
        res.statusCode = 400;
        res.end(JSON.stringify({ error: "Missing path parameter" }));
        return;
      }
      try {
        const meta = await scanner.getImageMeta(filepath);
        res.setHeader("Content-Type", "application/json");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.end(JSON.stringify(meta || null));
        return;
      } catch (e) {
        res.statusCode = 500;
        res.end(JSON.stringify({ error: "Failed to get image meta" }));
        return;
      }
    }
    if (url.pathname === "/__react_devtools__/api/assets/text-content") {
      const filepath = url.searchParams.get("path");
      const limit = Number.parseInt(url.searchParams.get("limit") || "500", 10);
      if (!filepath) {
        res.statusCode = 400;
        res.end(JSON.stringify({ error: "Missing path parameter" }));
        return;
      }
      try {
        const content = await scanner.getTextContent(filepath, limit);
        res.setHeader("Content-Type", "application/json");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.end(JSON.stringify({ content: content || null }));
        return;
      } catch (e) {
        res.statusCode = 500;
        res.end(JSON.stringify({ error: "Failed to get text content" }));
        return;
      }
    }
    next();
  };
}

// src/middleware/client-server.ts
import sirv from "sirv";
function serveClient(servePath) {
  return sirv(servePath, {
    single: true,
    dev: true
  });
}

// src/middleware/graph.ts
import fs2 from "fs";
import path5 from "path";
function createGraphMiddleware(getModuleGraph, base = "/") {
  const apiPath = `${base}__react_devtools_api__/graph`.replace(/\/+/g, "/");
  return async (req, res, next) => {
    const url = req.url || "";
    if (url === apiPath || url.startsWith(`${apiPath}?`)) {
      try {
        const data = await getModuleGraph();
        res.setHeader("Content-Type", "application/json");
        res.setHeader("Cache-Control", "no-cache");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.end(JSON.stringify(data));
      } catch (error) {
        console.error("[React DevTools] Failed to get module graph:", error);
        res.statusCode = 500;
        res.end(JSON.stringify({ error: "Failed to get module graph" }));
      }
    } else {
      next();
    }
  };
}
var webpackModuleGraph = { modules: [], root: "" };
function processModules(statsModules, modules, fileExtPattern) {
  const moduleMap = /* @__PURE__ */ new Map();
  statsModules.forEach((mod) => {
    const id = mod.name || mod.identifier || "";
    if (!id)
      return;
    if (!fileExtPattern.test(id))
      return;
    if (id.startsWith("webpack/") || id.startsWith("(webpack)"))
      return;
    const normalizedId = normalizeWebpackModulePath(id);
    if (!normalizedId)
      return;
    const isVirtual = !mod.resource || id.includes("\0") || id.includes("virtual:");
    if (!moduleMap.has(normalizedId)) {
      moduleMap.set(normalizedId, {
        id: normalizedId,
        deps: [],
        virtual: isVirtual
      });
    }
    if (mod.reasons && Array.isArray(mod.reasons)) {
      mod.reasons.forEach((reason) => {
        const depId = reason.moduleName || reason.moduleIdentifier || "";
        if (!depId)
          return;
        if (!fileExtPattern.test(depId))
          return;
        if (depId.startsWith("webpack/") || depId.startsWith("(webpack)"))
          return;
        const normalizedDepId = normalizeWebpackModulePath(depId);
        if (normalizedDepId && normalizedDepId !== normalizedId) {
          if (!moduleMap.has(normalizedDepId)) {
            moduleMap.set(normalizedDepId, {
              id: normalizedDepId,
              deps: [],
              virtual: false
            });
          }
          const depModule = moduleMap.get(normalizedDepId);
          if (!depModule.deps.includes(normalizedId)) {
            depModule.deps.push(normalizedId);
          }
        }
      });
    }
    if (mod.issuer) {
      const issuerId = normalizeWebpackModulePath(mod.issuer);
      if (issuerId && issuerId !== normalizedId && fileExtPattern.test(mod.issuer)) {
        if (!moduleMap.has(issuerId)) {
          moduleMap.set(issuerId, {
            id: issuerId,
            deps: [],
            virtual: false
          });
        }
        const issuerModule = moduleMap.get(issuerId);
        if (!issuerModule.deps.includes(normalizedId)) {
          issuerModule.deps.push(normalizedId);
        }
      }
    }
  });
  moduleMap.forEach((mod) => {
    const existing = modules.find((m) => m.id === mod.id);
    if (existing) {
      mod.deps.forEach((dep) => {
        if (!existing.deps.includes(dep)) {
          existing.deps.push(dep);
        }
      });
    } else {
      modules.push(mod);
    }
  });
}
function setupWebpackModuleGraph(compiler, root) {
  const fileExtPattern = /\.(?:tsx?|jsx?|vue|json|css|scss|less|html)(?:$|\?)/;
  compiler.hooks.compilation.tap("react-devtools-graph", (compilation) => {
    var _a;
    (_a = compilation.hooks.afterOptimizeModules) == null ? void 0 : _a.tap("react-devtools-graph", (compilationModules) => {
      var _a2, _b;
      try {
        const modules = [];
        const moduleMap = /* @__PURE__ */ new Map();
        for (const mod of compilationModules) {
          const resource = mod.resource || mod.userRequest || "";
          if (!resource)
            continue;
          if (!fileExtPattern.test(resource))
            continue;
          const normalizedPath = resource.replace(/\\/g, "/");
          const id = normalizedPath;
          if (!moduleMap.has(id)) {
            moduleMap.set(id, {
              id,
              deps: [],
              virtual: !mod.resource
            });
          }
          if (mod.dependencies) {
            for (const dep of mod.dependencies) {
              const depModule = (_b = (_a2 = compilation.moduleGraph) == null ? void 0 : _a2.getModule) == null ? void 0 : _b.call(_a2, dep);
              if (depModule) {
                const depResource = depModule.resource || depModule.userRequest || "";
                if (depResource && fileExtPattern.test(depResource)) {
                  const depId = depResource.replace(/\\/g, "/");
                  const currentModule = moduleMap.get(id);
                  if (!currentModule.deps.includes(depId)) {
                    currentModule.deps.push(depId);
                  }
                }
              }
            }
          }
        }
        moduleMap.forEach((mod) => {
          modules.push(mod);
        });
        if (modules.length > 0) {
          webpackModuleGraph = { modules, root };
          try {
            const graphDir = path5.join(root, ".next", "cache", "react-devtools");
            if (!fs2.existsSync(graphDir)) {
              fs2.mkdirSync(graphDir, { recursive: true });
            }
            const graphPath = path5.join(graphDir, "module-graph.json");
            fs2.writeFileSync(graphPath, JSON.stringify(webpackModuleGraph, null, 2));
          } catch (e) {
          }
        }
      } catch (error) {
        console.error("[React DevTools] Failed to collect module graph from compilation:", error);
      }
    });
  });
  compiler.hooks.done.tap("react-devtools-graph", (stats) => {
    if (webpackModuleGraph.modules.length > 0) {
      return;
    }
    try {
      const modules = [];
      const statsArray = stats.stats || [stats];
      for (const singleStats of statsArray) {
        if (typeof singleStats.toJson !== "function") {
          continue;
        }
        const statsData = singleStats.toJson({
          all: false,
          modules: true,
          reasons: true,
          children: true,
          nestedModules: true,
          dependentModules: true
        });
        if (statsData.children && Array.isArray(statsData.children) && statsData.children.length > 0) {
          for (const child of statsData.children) {
            if (child.modules && child.modules.length > 0) {
              processModules(child.modules, modules, fileExtPattern);
            }
          }
        }
        if (statsData.modules && statsData.modules.length > 0) {
          processModules(statsData.modules, modules, fileExtPattern);
        }
      }
      if (modules.length > 0) {
        webpackModuleGraph = { modules, root };
        try {
          const graphDir = path5.join(root, ".next", "cache", "react-devtools");
          if (!fs2.existsSync(graphDir)) {
            fs2.mkdirSync(graphDir, { recursive: true });
          }
          const graphPath = path5.join(graphDir, "module-graph.json");
          fs2.writeFileSync(graphPath, JSON.stringify(webpackModuleGraph, null, 2));
        } catch (e) {
        }
      }
    } catch (error) {
      console.error("[React DevTools] Failed to collect module graph:", error);
    }
  });
}
function normalizeWebpackModulePath(modulePath) {
  if (!modulePath)
    return null;
  let path10 = modulePath;
  const loaderIndex = path10.lastIndexOf("!");
  if (loaderIndex !== -1) {
    path10 = path10.substring(loaderIndex + 1);
  }
  const queryIndex = path10.indexOf("?");
  if (queryIndex !== -1) {
    path10 = path10.substring(0, queryIndex);
  }
  path10 = path10.replace(/^\.\//, "");
  path10 = path10.replace(/^!+/, "");
  if (!path10 || !path10.includes("/"))
    return null;
  return path10;
}
function getWebpackModuleGraph() {
  return async () => {
    return webpackModuleGraph;
  };
}

// src/middleware/open-in-editor.ts
import { exec } from "child_process";

// src/utils/paths.ts
import fs3 from "fs";
import path6 from "path";
function normalizePath(id) {
  return id.replace(/\\/g, "/");
}
var DEVTOOLS_OPTIONS_ID = "virtual:react-devtools-options";
var RESOLVED_OPTIONS_ID = `\0${DEVTOOLS_OPTIONS_ID}`;
function getPluginPath() {
  return normalizePath(DIR_DIST.replace(/\/dist$/, "/src"));
}
function getClientPath(reactDevtoolsPath) {
  const clientPath = path6.resolve(reactDevtoolsPath, "../../react-devtools-client");
  const oldClientPath = path6.resolve(reactDevtoolsPath, "../client");
  const clientDistPath = path6.resolve(clientPath, "dist");
  return fs3.existsSync(clientDistPath) && fs3.existsSync(path6.resolve(clientDistPath, "index.html")) ? clientDistPath : oldClientPath;
}
function convertToEditorPath(filePath, line, column) {
  const parts = [filePath];
  if (line !== void 0)
    parts.push(String(line));
  if (column !== void 0 && line !== void 0)
    parts.push(String(column));
  return parts.join(":");
}
function parseEditorPath(editorPath) {
  const parts = editorPath.split(":");
  const filePath = parts[0];
  const line = parts[1] ? Number.parseInt(parts[1], 10) : void 0;
  const column = parts[2] ? Number.parseInt(parts[2], 10) : void 0;
  return { filePath, line, column };
}
function resolveRelativeToAbsolute(relativePath, projectRoot, sourcePathMode) {
  if (sourcePathMode === "absolute" || path6.isAbsolute(relativePath)) {
    return relativePath;
  }
  const segments = relativePath.split("/");
  const pathFromRoot = segments.length > 1 ? segments.slice(1).join("/") : relativePath;
  return path6.resolve(projectRoot, pathFromRoot);
}

// src/middleware/open-in-editor.ts
async function openFileInEditor(filePath, projectRoot, sourcePathMode, launchEditor) {
  return new Promise((resolve2, reject) => {
    const { filePath: file, line, column } = parseEditorPath(filePath);
    const absolutePath = resolveRelativeToAbsolute(file, projectRoot, sourcePathMode);
    const editorPath = convertToEditorPath(absolutePath, line, column);
    const editorCmd = launchEditor || process.env.EDITOR || "code";
    const cmd = `${editorCmd} -g "${editorPath}"`;
    exec(cmd, (error) => {
      if (error) {
        console.error("[React DevTools] Failed to open editor:", error);
        reject(error);
      } else {
        resolve2();
      }
    });
  });
}
function createOpenInEditorMiddleware(projectRoot, sourcePathMode, launchEditor) {
  return async (req, res, next) => {
    var _a;
    if (!((_a = req.url) == null ? void 0 : _a.startsWith("/__open-in-editor"))) {
      next == null ? void 0 : next();
      return;
    }
    const url = new URL(req.url, `http://${req.headers.host}`);
    const file = url.searchParams.get("file");
    if (!file) {
      res.statusCode = 400;
      res.setHeader("Content-Type", "text/plain");
      res.end("Missing file parameter");
      return;
    }
    const editorFromClient = url.searchParams.get("editor");
    const effectiveEditor = launchEditor || editorFromClient || void 0;
    try {
      await openFileInEditor(file, projectRoot, sourcePathMode, effectiveEditor);
      res.statusCode = 200;
      res.setHeader("Content-Type", "text/plain");
      res.end("OK");
    } catch (error) {
      console.error("[React DevTools] Failed to execute editor command:", error.message);
      res.statusCode = 500;
      res.setHeader("Content-Type", "text/plain");
      res.end("Failed to open editor");
    }
  };
}

// src/middleware/plugin-file.ts
import fs4 from "fs";
import { transformSync } from "@babel/core";
function createPluginFileMiddleware() {
  return (req, res, next) => {
    const rawUrl = req.url || "";
    const url = new URL(rawUrl, "http://localhost");
    if (rawUrl.includes("__react_devtools__")) {
    }
    if (url.pathname === "/__react_devtools__/file") {
      const filePath = url.searchParams.get("path");
      if (!filePath) {
        console.error("[React DevTools] Plugin file middleware: Missing path parameter", req.url);
        res.statusCode = 400;
        res.end("Missing path parameter");
        return;
      }
      try {
        const decodedPath = decodeURIComponent(filePath);
        if (!fs4.existsSync(decodedPath)) {
          console.error("[React DevTools] Plugin file middleware: File not found", decodedPath);
          res.statusCode = 404;
          res.end("File not found");
          return;
        }
        const content = fs4.readFileSync(decodedPath, "utf-8");
        const isTs = decodedPath.endsWith(".ts") || decodedPath.endsWith(".tsx");
        const isJsx = decodedPath.endsWith(".jsx") || decodedPath.endsWith(".tsx");
        const result = transformSync(content, {
          filename: decodedPath,
          presets: [
            ["@babel/preset-react", {
              runtime: "classic",
              // Switch to classic runtime to avoid jsx-dev-runtime imports
              development: true
            }],
            ["@babel/preset-typescript", { isTSX: isJsx, allExtensions: true }]
          ],
          plugins: [
            // Simple plugin to rewrite "import React from 'react'" to "const React = window.React"
            function() {
              return {
                visitor: {
                  ImportDeclaration(path10) {
                    if (path10.node.source.value === "react") {
                      const defaultSpecifier = path10.node.specifiers.find(
                        (s) => s.type === "ImportDefaultSpecifier"
                      );
                      if (defaultSpecifier) {
                        const localName = defaultSpecifier.local.name;
                        path10.replaceWith({
                          type: "VariableDeclaration",
                          kind: "const",
                          declarations: [
                            {
                              type: "VariableDeclarator",
                              id: { type: "Identifier", name: localName },
                              init: {
                                type: "MemberExpression",
                                object: { type: "Identifier", name: "window" },
                                property: { type: "Identifier", name: "React" }
                              }
                            }
                          ]
                        });
                      } else {
                        const namespaceSpecifier = path10.node.specifiers.find(
                          (s) => s.type === "ImportNamespaceSpecifier"
                        );
                        if (namespaceSpecifier) {
                          const localName = namespaceSpecifier.local.name;
                          path10.replaceWith({
                            type: "VariableDeclaration",
                            kind: "const",
                            declarations: [
                              {
                                type: "VariableDeclarator",
                                id: { type: "Identifier", name: localName },
                                init: {
                                  type: "MemberExpression",
                                  object: { type: "Identifier", name: "window" },
                                  property: { type: "Identifier", name: "React" }
                                }
                              }
                            ]
                          });
                        } else {
                          path10.remove();
                        }
                      }
                    }
                  }
                }
              };
            }
          ]
        });
        res.setHeader("Content-Type", "application/javascript");
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.end((result == null ? void 0 : result.code) || "");
        return;
      } catch (e) {
        console.error("[React DevTools] Failed to transform plugin file:", e);
        res.statusCode = 500;
        res.end(JSON.stringify({ error: e.message }));
        return;
      }
    }
    next();
  };
}

// src/middleware/plugins.ts
function createPluginsMiddleware(config, transformPath) {
  return (req, res, next) => {
    const rawUrl = req.url || "";
    const url = new URL(rawUrl, "http://localhost");
    const isMatch = url.pathname === "/__react_devtools__/plugins-manifest.json";
    if (isMatch) {
      res.setHeader("Content-Type", "application/json");
      res.setHeader("Access-Control-Allow-Origin", "*");
      const plugins = (config.plugins || []).map((plugin) => {
        if (plugin.view && plugin.view.src && transformPath) {
          return __spreadProps(__spreadValues({}, plugin), {
            view: __spreadProps(__spreadValues({}, plugin.view), {
              src: transformPath(plugin.view.src)
            })
          });
        }
        return plugin;
      });
      res.end(JSON.stringify(plugins));
      return;
    }
    next();
  };
}

// src/middleware/next.ts
import fs5 from "fs";
import path7 from "path";
function createDevToolsApiHandler(config, clientPath) {
  const middlewares = [
    createPluginsMiddleware(config, (filePath) => {
      return `/__react_devtools__/file?path=${encodeURIComponent(filePath)}`;
    }),
    createPluginFileMiddleware(),
    createGraphMiddleware(getWebpackModuleGraph(), "/"),
    createOpenInEditorMiddleware(config.projectRoot, config.sourcePathMode, config.launchEditor),
    createAssetsMiddleware({
      root: config.projectRoot,
      publicDir: "public",
      baseUrl: "/"
    }),
    serveClient(clientPath)
  ];
  return async (req, res) => {
    for (const middleware of middlewares) {
      await new Promise((resolve2) => {
        let handled = false;
        middleware(req, res, () => {
          if (!handled) {
            handled = true;
            resolve2();
          }
        });
        if (res.writableEnded || res.headersSent) {
          handled = true;
          resolve2();
        }
      });
      if (res.writableEnded || res.headersSent) {
        return;
      }
    }
    res.statusCode = 404;
    res.end("Not found");
  };
}
function createDevToolsMiddleware(config, clientPath) {
  const handler = createDevToolsApiHandler(config, clientPath);
  return (req, res, next) => {
    var _a;
    if (!((_a = req.url) == null ? void 0 : _a.startsWith("/__react_devtools__"))) {
      return next();
    }
    const originalUrl = req.url;
    req.url = req.url.replace("/__react_devtools__", "") || "/";
    handler(req, res).then(() => {
      req.url = originalUrl;
      if (!res.writableEnded) {
        next();
      }
    }).catch((err) => {
      console.error("[React DevTools] Middleware error:", err);
      req.url = originalUrl;
      next();
    });
  };
}
function serveOverlayScript(overlayDir) {
  const overlayPath = path7.join(overlayDir, "react-devtools-overlay.mjs");
  return (req, res) => {
    if (req.url === "/__react_devtools__/overlay.mjs") {
      if (fs5.existsSync(overlayPath)) {
        res.setHeader("Content-Type", "application/javascript; charset=utf-8");
        res.setHeader("Cache-Control", "no-cache");
        res.end(fs5.readFileSync(overlayPath, "utf-8"));
        return true;
      }
    }
    return false;
  };
}

// src/utils/babel-transform.ts
import path8 from "path";
import { transformSync as transformSync2, types } from "@babel/core";
function createSourceAttributePlugin(projectRoot, pathMode) {
  return function sourceAttributePlugin() {
    return {
      name: "react-devtools-source-attribute",
      visitor: {
        JSXOpeningElement(nodePath) {
          var _a, _b;
          const loc = nodePath.node.loc;
          if (!loc)
            return;
          const filename = ((_b = (_a = this.file) == null ? void 0 : _a.opts) == null ? void 0 : _b.filename) || "";
          if (!filename)
            return;
          let finalPath = filename;
          if (pathMode === "relative" && path8.isAbsolute(filename) && projectRoot) {
            const parentDir = path8.dirname(projectRoot);
            finalPath = path8.relative(parentDir, filename);
            finalPath = finalPath.split(path8.sep).join("/");
          }
          nodePath.node.attributes.push(
            types.jsxAttribute(
              types.jsxIdentifier("data-source-path"),
              types.stringLiteral(`${finalPath}:${loc.start.line}:${loc.start.column}`)
            )
          );
        }
      }
    };
  };
}

// src/integrations/next.ts
var _clientPath = null;
var _pluginConfig = null;
function ensureCacheDir(projectRoot) {
  const cacheDir = path9.join(projectRoot, "node_modules", ".cache", "react-devtools-plus");
  if (!fs6.existsSync(cacheDir)) {
    fs6.mkdirSync(cacheDir, { recursive: true });
  }
  return cacheDir;
}
function writeInitFile(cacheDir, filename, content) {
  const filePath = path9.join(cacheDir, filename);
  fs6.writeFileSync(filePath, content, "utf-8");
  return filePath;
}
function getNextVersion(projectRoot) {
  try {
    const pkgPath = path9.join(projectRoot, "node_modules", "next", "package.json");
    if (fs6.existsSync(pkgPath)) {
      const pkg = JSON.parse(fs6.readFileSync(pkgPath, "utf-8"));
      const version = pkg.version;
      const major = Number.parseInt(version.split(".")[0], 10);
      return major;
    }
  } catch (e) {
  }
  return null;
}
function detectTurbopack(nextConfig) {
  var _a;
  return !!(((_a = nextConfig == null ? void 0 : nextConfig.experimental) == null ? void 0 : _a.turbo) || (nextConfig == null ? void 0 : nextConfig.turbopack));
}
function withReactDevTools(nextConfig, options = {}) {
  var _a, _b, _c, _d, _e;
  const projectRoot = process.cwd();
  const mode = process.env.NODE_ENV || "development";
  const isDev = mode === "development";
  const pluginConfig = resolvePluginConfig(
    options,
    projectRoot,
    mode,
    isDev ? "serve" : "build"
  );
  if (!(pluginConfig == null ? void 0 : pluginConfig.isEnabled)) {
    return nextConfig;
  }
  const reactDevtoolsPath = getPluginPath();
  const clientPath = getClientPath(reactDevtoolsPath);
  const nextVersion = getNextVersion(projectRoot);
  console.log("[React DevTools Plus] Initializing for Next.js", nextVersion ? `v${nextVersion}` : "");
  const usesTurbopack = detectTurbopack(nextConfig);
  const modifiedConfig = __spreadValues({}, nextConfig);
  if (isDev) {
    modifiedConfig.compiler = __spreadProps(__spreadValues({}, modifiedConfig.compiler || {}), {
      // Enable React development mode for _debugSource
      reactRemoveProperties: false
    });
    modifiedConfig.experimental = __spreadProps(__spreadValues({}, modifiedConfig.experimental || {}), {
      // Enable SWC's development mode for React
      swcPlugins: ((_a = modifiedConfig.experimental) == null ? void 0 : _a.swcPlugins) || []
    });
  }
  const turbopackRules = createTurbopackRules(pluginConfig, projectRoot, false);
  if (nextVersion && nextVersion >= 15) {
    modifiedConfig.turbopack = __spreadProps(__spreadValues({}, modifiedConfig.turbopack || {}), {
      rules: __spreadValues(__spreadValues({}, ((_b = modifiedConfig.turbopack) == null ? void 0 : _b.rules) || {}), turbopackRules)
    });
  } else if (usesTurbopack) {
    modifiedConfig.experimental = __spreadProps(__spreadValues({}, modifiedConfig.experimental || {}), {
      turbo: __spreadProps(__spreadValues({}, ((_c = modifiedConfig.experimental) == null ? void 0 : _c.turbo) || {}), {
        rules: __spreadValues(__spreadValues({}, ((_e = (_d = modifiedConfig.experimental) == null ? void 0 : _d.turbo) == null ? void 0 : _e.rules) || {}), turbopackRules)
      })
    });
  }
  const originalWebpack = modifiedConfig.webpack;
  modifiedConfig.webpack = (config, context) => {
    if (typeof originalWebpack === "function") {
      config = originalWebpack(config, context);
    }
    if (context.dev) {
      applyWebpackConfig(config, context, pluginConfig, projectRoot, clientPath);
    }
    return config;
  };
  const originalRewrites = modifiedConfig.rewrites;
  modifiedConfig.rewrites = async () => {
    const rewrites = typeof originalRewrites === "function" ? await originalRewrites() : originalRewrites || { beforeFiles: [], afterFiles: [], fallback: [] };
    const normalizedRewrites = Array.isArray(rewrites) ? { beforeFiles: [], afterFiles: rewrites, fallback: [] } : {
      beforeFiles: rewrites.beforeFiles || [],
      afterFiles: rewrites.afterFiles || [],
      fallback: rewrites.fallback || []
    };
    return normalizedRewrites;
  };
  return modifiedConfig;
}
function applyWebpackConfig(config, context, pluginConfig, projectRoot, clientPath) {
  if (pluginConfig.injectSource) {
    const babelPlugin = createSourceAttributePlugin(
      pluginConfig.projectRoot,
      pluginConfig.sourcePathMode
    );
    injectBabelPluginToNextConfig(config, babelPlugin, projectRoot);
  }
  if (context.isServer) {
    return;
  }
  const cacheDir = ensureCacheDir(projectRoot);
  const filesToInject = [];
  const configCode = generateConfigInjectionCode({
    clientUrl: pluginConfig.clientUrl,
    rootSelector: pluginConfig.rootSelector,
    theme: pluginConfig.theme,
    assets: pluginConfig.assets
  });
  if (configCode) {
    const configPath = writeInitFile(cacheDir, "devtools-config.js", configCode);
    filesToInject.push(configPath);
  }
  const globalsInitCode = generateGlobalsWithCSSCode(DIR_OVERLAY);
  const globalsInitPath = writeInitFile(cacheDir, "react-globals-init.js", globalsInitCode);
  filesToInject.push(globalsInitPath);
  const overlayPath = path9.join(DIR_OVERLAY, "react-devtools-overlay.mjs");
  if (fs6.existsSync(overlayPath)) {
    filesToInject.push(overlayPath);
  }
  if (config.entry) {
    const originalEntry = config.entry;
    config.entry = async () => {
      const entries = typeof originalEntry === "function" ? await originalEntry() : originalEntry;
      const mainKeys = ["main-app", "main", "pages/_app"];
      for (const mainKey of mainKeys) {
        if (entries[mainKey]) {
          const currentEntry = entries[mainKey];
          if (currentEntry.import) {
            entries[mainKey] = __spreadProps(__spreadValues({}, currentEntry), {
              import: [...filesToInject, ...currentEntry.import]
            });
          }
          break;
        }
      }
      return entries;
    };
  }
  const DevToolsPlugin = createNextDevToolsPlugin(
    pluginConfig,
    projectRoot,
    clientPath
  );
  config.plugins.push(new DevToolsPlugin());
}
function createTurbopackRules(pluginConfig, projectRoot, verbose = true) {
  const cacheDir = ensureCacheDir(projectRoot);
  const configCode = generateConfigInjectionCode({
    clientUrl: pluginConfig.clientUrl,
    rootSelector: pluginConfig.rootSelector,
    theme: pluginConfig.theme,
    assets: pluginConfig.assets
  });
  if (configCode) {
    writeInitFile(cacheDir, "devtools-config.js", configCode);
  }
  const globalsInitCode = generateGlobalsWithCSSCode(DIR_OVERLAY);
  writeInitFile(cacheDir, "react-globals-init.js", globalsInitCode);
  const loaderPath = path9.join(
    path9.dirname(__require.resolve("react-devtools-plus/package.json")),
    "dist",
    "next-loader.js"
  );
  if (verbose) {
    console.log("[React DevTools Plus] Turbopack rules prepared - will be used if --turbopack flag is set");
  }
  return {};
}
function createNextDevToolsPlugin(pluginConfig, projectRoot, clientPath) {
  _pluginConfig = pluginConfig;
  _clientPath = clientPath;
  return class ReactDevToolsNextPlugin {
    apply(compiler) {
      setupWebpackModuleGraph(compiler, projectRoot);
      if (compiler.options.mode === "development") {
        const devToolsMiddleware = createDevToolsMiddleware(pluginConfig, clientPath);
        const overlayMiddleware = serveOverlayScript(DIR_OVERLAY);
        globalThis.__REACT_DEVTOOLS_MIDDLEWARE__ = devToolsMiddleware;
        globalThis.__REACT_DEVTOOLS_OVERLAY_MIDDLEWARE__ = overlayMiddleware;
        compiler.hooks.afterEnvironment.tap("ReactDevToolsNextPlugin", () => {
          console.log("[React DevTools Plus] Ready");
          console.log("[React DevTools Plus] Access DevTools at http://localhost:3000/__react_devtools__/");
          console.log("[React DevTools Plus] Press Option(\u2325)+Shift(\u21E7)+D to toggle panel");
        });
      }
    }
  };
}
function injectBabelPluginToNextConfig(config, plugin, projectRoot) {
  var _a;
  if (!((_a = config.module) == null ? void 0 : _a.rules))
    config.module = { rules: [] };
  if (!config.module.rules)
    config.module.rules = [];
  let foundBabelLoader = false;
  for (const rule of config.module.rules) {
    if (!rule)
      continue;
    if (rule.oneOf) {
      for (const oneOfRule of rule.oneOf) {
        if (injectPluginToRule(oneOfRule, plugin)) {
          foundBabelLoader = true;
        }
      }
    } else {
      if (injectPluginToRule(rule, plugin)) {
        foundBabelLoader = true;
      }
    }
  }
  if (!foundBabelLoader) {
    const sourceInjectionRule = {
      test: /\.(jsx|tsx)$/,
      exclude: /node_modules/,
      enforce: "pre",
      // Run BEFORE other loaders (including SWC)
      use: [
        {
          loader: "babel-loader",
          options: {
            // Only use our plugin - don't transform the code
            presets: [
              ["@babel/preset-react", { runtime: "automatic" }],
              "@babel/preset-typescript"
            ],
            plugins: [plugin],
            // Don't use external babel config
            configFile: false,
            babelrc: false,
            // Cache for performance
            cacheDirectory: true,
            cacheCompression: false,
            // Output source maps for accurate source locations
            sourceMaps: true
          }
        }
      ]
    };
    config.module.rules.push(sourceInjectionRule);
    console.log("[React DevTools Plus] Added babel-loader for source path injection (pre-SWC)");
  }
}
function injectPluginToRule(rule, plugin) {
  if (!(rule == null ? void 0 : rule.use))
    return false;
  const uses = Array.isArray(rule.use) ? rule.use : [rule.use];
  let found = false;
  for (const use of uses) {
    if (!use)
      continue;
    const loaderName = typeof use === "string" ? use : use.loader;
    if (loaderName && (loaderName.includes("babel-loader") || loaderName.includes("next-babel-loader"))) {
      if (typeof use !== "string") {
        if (!use.options)
          use.options = {};
        if (!use.options.plugins)
          use.options.plugins = [];
        use.options.plugins.push(plugin);
        found = true;
      }
    }
  }
  return found;
}
function createNextPlugin(options = {}) {
  const projectRoot = process.cwd();
  const mode = process.env.NODE_ENV || "development";
  const isDev = mode === "development";
  const pluginConfig = resolvePluginConfig(
    options,
    projectRoot,
    mode,
    isDev ? "serve" : "build"
  );
  if (!(pluginConfig == null ? void 0 : pluginConfig.isEnabled)) {
    return {
      apply() {
      }
    };
  }
  const reactDevtoolsPath = getPluginPath();
  const clientPath = getClientPath(reactDevtoolsPath);
  return createNextDevToolsPlugin(pluginConfig, projectRoot, clientPath);
}

// src/next.ts
var next_default = withReactDevTools;
export {
  createNextPlugin,
  next_default as default,
  withReactDevTools
};
//# sourceMappingURL=next.js.map