import {
  require_browser
} from "./chunk-chunk-LLVGV6IH.mjs";
import {
  wait
} from "./chunk-chunk-YPDNFE33.mjs";
import {
  Mutex
} from "./chunk-chunk-F7WP42AK.mjs";
import {
  importMapReplace
} from "./chunk-chunk-DZONV6IJ.mjs";
import {
  md5
} from "./chunk-chunk-RGRIKHHV.mjs";
import {
  importMap
} from "./chunk-chunk-DUODS2QA.mjs";
import {
  __name,
  __toESM,
  init_define_process
} from "./chunk-chunk-5RXWZEI4.mjs";

// src/esbuildEsmBuild.ts
init_define_process();
var import_esbuild_wasm = __toESM(require_browser(), 1);

// src/fetchPlugin.tsx
init_define_process();
var fetchPlugin = /* @__PURE__ */ __name((transform2) => ({
  name: "http",
  setup(build) {
    build.onResolve(
      { filter: /^https?:\/\//, namespace: "http-url" },
      (args) => ({
        path: new URL(
          args.path.indexOf("/live/") !== -1 && args.path.indexOf(".tsx") === -1 ? `${args.path}/index.tsx` : args.path,
          args.importer
        ).toString(),
        namespace: "http-url"
      })
    );
    build.onResolve({ filter: /^[a-z]+/, namespace: "http-url" }, (args) => ({
      path: Object.keys(importMap.imports).includes(args.path) ? args.path : `https://esm.sh/*${args.path}?bundle=true`,
      namespace: "http-url"
    }));
    build.onResolve({ filter: /\.ttf*/, namespace: "http-url" }, (args) => ({
      path: new URL(args.path, args.importer).toString(),
      namespace: "ttf"
    }));
    build.onLoad({ filter: /.*/ }, async (args) => {
      const req = new Request(args.path);
      let response = await getRequest(req);
      if (args.namespace === "ttf") {
        let contents = await response.arrayBuffer();
        response = new Response(contents, response);
        const z = new Uint8Array(contents, 1, 4);
        return {
          contents: z,
          loader: "dataurl"
        };
      }
      const code = await response.text();
      if (args.path.indexOf(".tsx") !== -1) {
        return {
          contents: await transform2(code)
        };
      }
      return { contents: code };
    });
  }
}), "fetchPlugin");
async function getRequest(req) {
  console.log({ getReq: req });
  let response = await fetch(req);
  if (!(response == null ? void 0 : response.ok))
    return response;
  response = new Response(response.body, response);
  return response;
}
__name(getRequest, "getRequest");

// src/unpkg-path-plugin.tsx
init_define_process();
var unpkgPathPlugin = /* @__PURE__ */ __name((origin) => ({
  name: "unpkg-path-plugin",
  setup(build) {
    build.onResolve({ filter: /^\.+\// }, (args) => {
      const url = new URL(args.path, location.origin).toString();
      return {
        path: url,
        namespace: "http-url"
      };
    });
    build.onResolve({ filter: /^\[a-z]+\// }, (args) => {
      if (args.path.indexOf(origin) !== -1) {
        return {
          namespace: "http-url",
          path: args.path
        };
      }
      return {
        path: `${origin}/*${args.path}?bundle?target=es2022&format=esm`,
        namespace: "http-url"
      };
    });
  }
}), "unpkgPathPlugin");

// src/esbuildEsmBuild.ts
var initDone = false;
var mutex = new Mutex();
var init = /* @__PURE__ */ __name((orig) => {
  if (initDone === false) {
    (async () => {
      await mutex.waitForUnlock();
      if (initDone)
        return;
      await mutex.acquire();
      await (0, import_esbuild_wasm.initialize)({
        wasmURL: `${orig}/esbuild-wasm@${import_esbuild_wasm.version}/esbuild.wasm`
      });
      initDone = true;
      mutex.release();
    })();
  }
}, "init");
var initAndTransform = /* @__PURE__ */ __name(async (code, opts, origin) => {
  if (initDone === false)
    await mutex.waitForUnlock();
  await mutex.acquire();
  await mutex.release();
  init(origin);
  await wait(100);
  await mutex.waitForUnlock();
  const ttCode = await (0, import_esbuild_wasm.transform)(code, {
    ...opts,
    define: { ...define, ...(opts == null ? void 0 : opts.define) ? opts.define : {} }
  });
  const res = { code: `/*${md5(code)}*/${ttCode.code}` };
  return res;
}, "initAndTransform");
var makeEnv = /* @__PURE__ */ __name((environment) => ({
  "process.env.NODE_ENV": `"${environment}"`,
  "process.env.NODE_DEBUG": JSON.stringify(false),
  "process.browser": JSON.stringify(true),
  "process.env.DEBUG": JSON.stringify(false),
  "isBrowser": JSON.stringify(true),
  "isJest": JSON.stringify(false),
  "process.env.version": '"1.1.1"',
  global: "globalThis",
  "WORKER_DOM_DEBUG": JSON.stringify(false),
  "process.env.DUMP_SESSION_KEYS": JSON.stringify(false),
  // "libFileMap": JSON.stringify({}),
  process: JSON.stringify({
    version: "v19.5.0",
    versions: {
      node: "v19.5.0"
    },
    cwd: JSON.stringify(() => "/"),
    env: {
      NODE_ENV: `${environment}`,
      version: "v19.5.0",
      cwd: JSON.stringify(() => "/"),
      browser: true,
      isWebworker: true,
      NODE_DEBUG: false,
      DEBUG: false,
      isBrowser: true,
      versions: {
        node: "v19.5.0"
      }
    },
    browser: true
  })
}), "makeEnv");
var define = makeEnv("development");
var skipImportmapReplaceNames = false;
var transformTsx = /* @__PURE__ */ __name((code) => (0, import_esbuild_wasm.transform)(code, {
  loader: "tsx",
  format: "esm",
  treeShaking: true,
  platform: "browser",
  minify: false,
  //   globalName: md5(code),
  keepNames: true,
  tsconfigRaw: {
    compilerOptions: {
      jsx: "react-jsx",
      useDefineForClassFields: false,
      jsxFragmentFactory: "Fragment",
      jsxImportSource: "@emotion/react"
    }
  },
  target: "chrome88"
}).then((r) => r.code), "transformTsx");
var buildT = /* @__PURE__ */ __name(async (codeSpace, origin, signal, opts = { bundle: false }) => {
  var _a;
  if (initDone === false)
    await mutex.waitForUnlock();
  await mutex.acquire();
  await mutex.release();
  init(origin);
  await wait(100);
  await mutex.waitForUnlock();
  const defaultOpts = {
    resolveExtensions: [
      ".tsx",
      ".ts",
      ".jsx",
      ".js",
      ".d.ts",
      ".css",
      ".json",
      ".mjs",
      ".js",
      ".wasm",
      ".ttf"
    ],
    loader: {
      ".js": "js",
      ".mjs": "js",
      ".json": "json",
      ".tsx": "tsx",
      ".css": "css",
      ".ttf": "dataurl"
    },
    outExtension: { ".js": ".mjs" },
    write: false,
    external: Object.keys(importMap.imports),
    // metafile: false,
    // alias: {
    //  ...importMap.imports,
    // },
    target: "chrome88",
    outdir: `./live/${codeSpace}`,
    treeShaking: true,
    minify: false,
    define,
    minifyIdentifiers: false,
    minifySyntax: false,
    minifyWhitespace: false,
    splitting: true,
    // incremental: true,
    // jsxImportSource: "@emotion/react",
    format: "esm",
    entryPoints: [
      `./live/${codeSpace}/index.tsx`
      // `./live/${codeSpace}/index.tsx`,
      // "./reactDomClient.mjs",
      // "./emotion.mjs",
      // "./motion.mjs",
      // "./emotionCache.mjs",
      // "./emotionStyled.mjs",
      // "./reactMod.mjs",
      // "./reactDom.mjs",
    ],
    tsconfig: "./tsconfig.json",
    plugins: [unpkgPathPlugin(origin), fetchPlugin(transformTsx)],
    ...opts
  };
  let b;
  if (!signal.aborted && (b = await (0, import_esbuild_wasm.build)(defaultOpts)) && !signal.aborted) {
    console.log(b.outputFiles);
    const { readdir, unlink, writeFile } = await import("./chunk-memfs-SFQHD2OJ.mjs");
    const cs = await readdir(`/live/${codeSpace}`);
    cs.filter((x) => x.indexOf("chunk") !== -1).map(
      (chunk) => {
        var _a2;
        return ((_a2 = b.outputFiles) == null ? void 0 : _a2.find((x) => x.path.indexOf(chunk) !== -1)) || unlink(`/live/${codeSpace}/${chunk}`);
      }
    );
    (_a = b.outputFiles) == null ? void 0 : _a.map(async (f) => {
      const file = f.path.split("/").pop();
      if (signal.aborted)
        return;
      if (cs.includes(file) && file.indexOf("chunk") === -1) {
        await unlink(f.path);
      }
      if ((file == null ? void 0 : file.indexOf("chunk")) === -1 || !cs.includes(file)) {
        await writeFile(
          f.path,
          importMapReplace(f.contents).split(`origin/`).join(origin + "/")
        );
      }
    });
    return b.outputFiles[0].text;
  }
  return false;
}, "buildT");
export {
  buildT,
  initAndTransform,
  skipImportmapReplaceNames,
  initAndTransform as transform
};
