"use strict";
var _a;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const events = require("./fetch-virtual-server-J6SUa9HS.cjs");
const dynamicImport = new Function(
  "specifier",
  "return import(specifier)"
);
const CJS_REQUIRE_HELPER = "__almostnodeRequire";
const isNodeLike = typeof process !== "undefined" && Boolean((_a = process.versions) == null ? void 0 : _a.node);
const isLikelyJsdom = typeof navigator !== "undefined" && /jsdom/i.test(navigator.userAgent || "");
const isBrowser = typeof window !== "undefined" && typeof document !== "undefined" && !isNodeLike && !isLikelyJsdom;
const NODE_BUILTINS = /* @__PURE__ */ new Set([
  "assert",
  "buffer",
  "child_process",
  "cluster",
  "crypto",
  "dgram",
  "dns",
  "events",
  "fs",
  "http",
  "http2",
  "https",
  "net",
  "os",
  "path",
  "perf_hooks",
  "querystring",
  "readline",
  "stream",
  "string_decoder",
  "timers",
  "tls",
  "url",
  "util",
  "v8",
  "vm",
  "worker_threads",
  "zlib",
  "async_hooks",
  "inspector",
  "module"
]);
function walkAst(node, callback, parent = null) {
  if (!node || typeof node !== "object") return;
  if (typeof node.type === "string") {
    callback(node, parent);
  }
  for (const key of Object.keys(node)) {
    if (key === "type" || key === "start" || key === "end" || key === "loc" || key === "range") continue;
    const child = node[key];
    if (child && typeof child === "object") {
      if (Array.isArray(child)) {
        for (const item of child) {
          if (item && typeof item === "object" && typeof item.type === "string") {
            walkAst(item, callback, node);
          }
        }
      } else if (typeof child.type === "string") {
        walkAst(child, callback, node);
      }
    }
  }
}
function parseDynamicImportAst(code) {
  const parse = (sourceType) => events.parse3(code, { ecmaVersion: "latest", sourceType });
  try {
    return parse("module");
  } catch {
    try {
      return parse("script");
    } catch {
      return null;
    }
  }
}
function applyReplacements(code, replacements) {
  if (replacements.length === 0) return code;
  let patched = code;
  replacements.sort((a, b) => b[0] - a[0]);
  for (const [start, end, replacement] of replacements) {
    patched = patched.slice(0, start) + replacement + patched.slice(end);
  }
  return patched;
}
function rewriteDynamicImportsForCjs(code) {
  const ast = parseDynamicImportAst(code);
  if (!ast) {
    return code;
  }
  const replacements = [];
  walkAst(ast, (node, parent) => {
    var _a2, _b, _c;
    if (node.type === "AwaitExpression") {
      const awaited = node.argument;
      if ((awaited == null ? void 0 : awaited.type) === "ImportExpression" && awaited.source) {
        const sourceCode2 = code.slice(awaited.source.start, awaited.source.end);
        replacements.push([node.start, node.end, `${CJS_REQUIRE_HELPER}(${sourceCode2})`]);
        return;
      }
      if ((awaited == null ? void 0 : awaited.type) === "CallExpression" && ((_a2 = awaited.callee) == null ? void 0 : _a2.type) === "Identifier" && awaited.callee.name === "__dynamicImport" && ((_b = awaited.arguments) == null ? void 0 : _b.length) === 1) {
        const arg = awaited.arguments[0];
        const sourceCode2 = code.slice(arg.start, arg.end);
        replacements.push([node.start, node.end, `${CJS_REQUIRE_HELPER}(${sourceCode2})`]);
      }
      return;
    }
    if (node.type !== "ImportExpression") {
      return;
    }
    if ((parent == null ? void 0 : parent.type) === "AwaitExpression" && parent.argument === node) {
      return;
    }
    if (((_c = node.source) == null ? void 0 : _c.type) !== "Literal" || typeof node.source.value !== "string") {
      return;
    }
    const specifier = node.source.value;
    if (!specifier.startsWith("node:") && !NODE_BUILTINS.has(specifier)) {
      return;
    }
    const sourceCode = code.slice(node.source.start, node.source.end);
    replacements.push([node.start, node.end, `Promise.resolve(${CJS_REQUIRE_HELPER}(${sourceCode}))`]);
  });
  return applyReplacements(code, replacements);
}
async function initTransformer() {
  if (!isBrowser) {
    console.log("[transform] Skipping esbuild init (not in browser)");
    return;
  }
  if (window.__esbuild) {
    console.log("[transform] Reusing existing esbuild instance");
    return;
  }
  if (window.__esbuildInitPromise) {
    return window.__esbuildInitPromise;
  }
  if (window.__esbuildInitFailed) {
    throw new Error("esbuild initialization previously failed permanently");
  }
  window.__esbuildInitPromise = (async () => {
    try {
      console.log("[transform] Loading esbuild-wasm...");
      const mod = await dynamicImport(events.ESBUILD_WASM_ESM_CDN);
      const esbuildMod = mod.default || mod;
      try {
        await esbuildMod.initialize({
          wasmURL: events.ESBUILD_WASM_BINARY_CDN
        });
        console.log("[transform] esbuild-wasm initialized");
      } catch (initError) {
        if (initError instanceof Error && initError.message.includes('Cannot call "initialize" more than once')) {
          console.log("[transform] esbuild-wasm already initialized, reusing");
        } else {
          throw initError;
        }
      }
      window.__esbuild = esbuildMod;
    } catch (error) {
      console.error("[transform] Failed to initialize esbuild:", error);
      window.__esbuildInitFailed = true;
      window.__esbuildInitPromise = void 0;
      throw error;
    }
  })();
  return window.__esbuildInitPromise;
}
function isTransformerReady() {
  if (!isBrowser) return true;
  return window.__esbuild !== void 0;
}
async function transformFile(code, filename) {
  if (!isBrowser) {
    return code;
  }
  if (!window.__esbuild) {
    await initTransformer();
  }
  const esbuild = window.__esbuild;
  if (!esbuild) {
    throw new Error("esbuild not initialized");
  }
  let loader = "js";
  if (filename.endsWith(".jsx")) loader = "jsx";
  else if (filename.endsWith(".ts")) loader = "ts";
  else if (filename.endsWith(".tsx")) loader = "tsx";
  else if (filename.endsWith(".mjs")) loader = "js";
  const rewriteAwaitImportsForCjs = (input) => rewriteDynamicImportsForCjs(input);
  const runTransform = async (inputCode) => {
    const result = await esbuild.transform(inputCode, {
      loader,
      format: "cjs",
      target: "esnext",
      platform: "neutral",
      // Replace import.meta with our runtime-provided variable
      // This is the proper esbuild way to handle import.meta in CJS
      define: {
        "import.meta.url": "import_meta.url",
        "import.meta.dirname": "import_meta.dirname",
        "import.meta.filename": "import_meta.filename",
        "import.meta": "import_meta"
      }
    });
    let transformed = result.code;
    return rewriteAwaitImportsForCjs(transformed);
  };
  try {
    return await runTransform(code);
  } catch (error) {
    const errorMsg = error instanceof Error ? error.message : String(error);
    if (errorMsg.includes("Top-level await")) {
      const rewritten = rewriteAwaitImportsForCjs(code);
      if (rewritten !== code) {
        try {
          return await runTransform(rewritten);
        } catch (rewriteError) {
          console.warn(`[transform] Top-level await rewrite failed for ${filename}:`, rewriteError);
        }
      }
      console.log(`[transform] Skipping ${filename} (has unsupported top-level await)`);
      return code;
    }
    console.warn(`[transform] Failed to transform ${filename}:`, error);
    return code;
  }
}
function needsTransform(filename, code) {
  if (filename.endsWith(".mjs")) {
    return true;
  }
  if (filename.endsWith(".cjs")) {
    return false;
  }
  const hasImport = /\bimport\s+[\w{*'"]/m.test(code);
  const hasExport = /\bexport\s+(?:default|const|let|var|function|class|{|\*)/m.test(code);
  const hasImportMeta = /\bimport\.meta\b/.test(code);
  const hasDynamicImport = /\bimport\s*\(/.test(code);
  return hasImport || hasExport || hasImportMeta || hasDynamicImport;
}
function hasDynamicNodeImports(code) {
  if (/\bimport\s*\(\s*["']node:/.test(code)) {
    return true;
  }
  if (/\bimport\s*\(\s*["'](fs|path|http|https|net|url|util|events|stream|os|crypto)["']/.test(code)) {
    return true;
  }
  return false;
}
function patchDynamicImports(code) {
  return rewriteDynamicImportsForCjs(code);
}
async function transformPackage(vfs, pkgPath, onProgress) {
  let transformedCount = 0;
  const jsFiles = findJsFiles(vfs, pkgPath);
  onProgress == null ? void 0 : onProgress(`  Transforming ${jsFiles.length} files in ${pkgPath}...`);
  const BATCH_SIZE = 10;
  for (let i = 0; i < jsFiles.length; i += BATCH_SIZE) {
    const batch = jsFiles.slice(i, i + BATCH_SIZE);
    await Promise.all(
      batch.map(async (filePath) => {
        try {
          const code = vfs.readFileSync(filePath, "utf8");
          if (needsTransform(filePath, code)) {
            const transformed = await transformFile(code, filePath);
            vfs.writeFileSync(filePath, transformed);
            transformedCount++;
          } else if (hasDynamicNodeImports(code)) {
            const patched = patchDynamicImports(code);
            vfs.writeFileSync(filePath, patched);
            transformedCount++;
          }
        } catch (error) {
          console.warn(`[transform] Skipping ${filePath}:`, error);
        }
      })
    );
  }
  return transformedCount;
}
function findJsFiles(vfs, dir) {
  const files = [];
  try {
    const entries = vfs.readdirSync(dir);
    for (const entry of entries) {
      const fullPath = dir + "/" + entry;
      try {
        const stat = vfs.statSync(fullPath);
        if (stat.isDirectory()) {
          if (entry !== "node_modules") {
            files.push(...findJsFiles(vfs, fullPath));
          }
        } else if (entry.endsWith(".js") || entry.endsWith(".mjs") || entry.endsWith(".jsx")) {
          files.push(fullPath);
        }
      } catch {
      }
    }
  } catch {
  }
  return files;
}
exports.initTransformer = initTransformer;
exports.isTransformerReady = isTransformerReady;
exports.patchDynamicImports = patchDynamicImports;
exports.transformFile = transformFile;
exports.transformPackage = transformPackage;
//# sourceMappingURL=transform-jXfghBBl.cjs.map
